diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/TextureResource.js b/src/core/textures/resources/TextureResource.js index 6f73793..7516c1e 100644 --- a/src/core/textures/resources/TextureResource.js +++ b/src/core/textures/resources/TextureResource.js @@ -4,7 +4,7 @@ { constructor(source) { - this.source = source; + this.source = source; this.loaded = false; // TODO rename to ready? @@ -21,6 +21,6 @@ destroy() { - console.warn(this, ' has no destroy function') + // somthing } -} \ No newline at end of file +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/TextureResource.js b/src/core/textures/resources/TextureResource.js index 6f73793..7516c1e 100644 --- a/src/core/textures/resources/TextureResource.js +++ b/src/core/textures/resources/TextureResource.js @@ -4,7 +4,7 @@ { constructor(source) { - this.source = source; + this.source = source; this.loaded = false; // TODO rename to ready? @@ -21,6 +21,6 @@ destroy() { - console.warn(this, ' has no destroy function') + // somthing } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/VideoResource.js b/src/core/textures/resources/VideoResource.js index 3402f96..1d6f5f8 100644 --- a/src/core/textures/resources/VideoResource.js +++ b/src/core/textures/resources/VideoResource.js @@ -1,8 +1,5 @@ import TextureResource from './TextureResource'; import * as ticker from '../../ticker'; -import { - uid -} from '../../utils'; export default class VideoResource extends TextureResource { @@ -34,7 +31,6 @@ source.addEventListener('play', this._onPlayStart.bind(this)); source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { source.addEventListener('canplay', this._onCanPlay); @@ -45,20 +41,20 @@ this._onCanPlay(); } - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { this.resolve = resolve; - if(this.loaded) + if (this.loaded) { this.resolve(this); } - }) + }); } update() { - //TODO - slow down and base on the videos framerate + // TODO - slow down and base on the videos framerate this.resourceUpdated.emit(); } @@ -127,7 +123,6 @@ */ _onCanPlay() { - if (this.source) { this.source.removeEventListener('canplay', this._onCanPlay); @@ -140,7 +135,7 @@ if (!this.loaded) { this.loaded = true; - if(this.resolve) + if (this.resolve) { this.resolve(this); } @@ -154,7 +149,6 @@ { this.source.play(); } - } } @@ -179,32 +173,6 @@ } /** - * Mimic Pixi BaseTexture.from.... method. - * - * @static - * @param {HTMLVideoElement} video - Video to create texture from - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - static fromVideo(video, scaleMode) - { - if (!video._pixiId) - { - video._pixiId = `video_${uid()}`; - } - - let baseTexture = BaseTextureCache[video._pixiId]; - - if (!baseTexture) - { - baseTexture = new VideoBaseTexture(video, scaleMode); - BaseTextureCache[video._pixiId] = baseTexture; - } - - return baseTexture; - } - - /** * Should the base texture automatically update itself, set to true by default * * @member {boolean} @@ -271,10 +239,8 @@ return new VideoResource(video, scaleMode); } - } - function createSource(path, type) { if (!type) diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/TextureResource.js b/src/core/textures/resources/TextureResource.js index 6f73793..7516c1e 100644 --- a/src/core/textures/resources/TextureResource.js +++ b/src/core/textures/resources/TextureResource.js @@ -4,7 +4,7 @@ { constructor(source) { - this.source = source; + this.source = source; this.loaded = false; // TODO rename to ready? @@ -21,6 +21,6 @@ destroy() { - console.warn(this, ' has no destroy function') + // somthing } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/VideoResource.js b/src/core/textures/resources/VideoResource.js index 3402f96..1d6f5f8 100644 --- a/src/core/textures/resources/VideoResource.js +++ b/src/core/textures/resources/VideoResource.js @@ -1,8 +1,5 @@ import TextureResource from './TextureResource'; import * as ticker from '../../ticker'; -import { - uid -} from '../../utils'; export default class VideoResource extends TextureResource { @@ -34,7 +31,6 @@ source.addEventListener('play', this._onPlayStart.bind(this)); source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { source.addEventListener('canplay', this._onCanPlay); @@ -45,20 +41,20 @@ this._onCanPlay(); } - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { this.resolve = resolve; - if(this.loaded) + if (this.loaded) { this.resolve(this); } - }) + }); } update() { - //TODO - slow down and base on the videos framerate + // TODO - slow down and base on the videos framerate this.resourceUpdated.emit(); } @@ -127,7 +123,6 @@ */ _onCanPlay() { - if (this.source) { this.source.removeEventListener('canplay', this._onCanPlay); @@ -140,7 +135,7 @@ if (!this.loaded) { this.loaded = true; - if(this.resolve) + if (this.resolve) { this.resolve(this); } @@ -154,7 +149,6 @@ { this.source.play(); } - } } @@ -179,32 +173,6 @@ } /** - * Mimic Pixi BaseTexture.from.... method. - * - * @static - * @param {HTMLVideoElement} video - Video to create texture from - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - static fromVideo(video, scaleMode) - { - if (!video._pixiId) - { - video._pixiId = `video_${uid()}`; - } - - let baseTexture = BaseTextureCache[video._pixiId]; - - if (!baseTexture) - { - baseTexture = new VideoBaseTexture(video, scaleMode); - BaseTextureCache[video._pixiId] = baseTexture; - } - - return baseTexture; - } - - /** * Should the base texture automatically update itself, set to true by default * * @member {boolean} @@ -271,10 +239,8 @@ return new VideoResource(video, scaleMode); } - } - function createSource(path, type) { if (!type) diff --git a/src/core/textures/resources/createResource.js b/src/core/textures/resources/createResource.js index f3fa500..60fdba6 100644 --- a/src/core/textures/resources/createResource.js +++ b/src/core/textures/resources/createResource.js @@ -5,26 +5,24 @@ export default function createResource(source) { - if (typeof source === 'string') - { + if (typeof source === 'string') + { // check if its a video.. if (source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)) { - return new VideoResource.fromUrl(source); - //video! - //return Texture.fromVideoUrl(source); - //return SVGResource.from(url); + return new VideoResource.fromUrl(source); + // video! + // return Texture.fromVideoUrl(source); + // return SVGResource.from(url); } else if (source.match(/\.(svg)$/)) { // SVG return SVGResource.from(source); } - else - { + // probably an image! - return ImageResource.from(source); - } + return ImageResource.from(source); } else if (source instanceof HTMLImageElement) { @@ -38,8 +36,6 @@ { return new VideoResource(source); } - else - { - return source; - } -} \ No newline at end of file + + return source; +} diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/TextureResource.js b/src/core/textures/resources/TextureResource.js index 6f73793..7516c1e 100644 --- a/src/core/textures/resources/TextureResource.js +++ b/src/core/textures/resources/TextureResource.js @@ -4,7 +4,7 @@ { constructor(source) { - this.source = source; + this.source = source; this.loaded = false; // TODO rename to ready? @@ -21,6 +21,6 @@ destroy() { - console.warn(this, ' has no destroy function') + // somthing } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/VideoResource.js b/src/core/textures/resources/VideoResource.js index 3402f96..1d6f5f8 100644 --- a/src/core/textures/resources/VideoResource.js +++ b/src/core/textures/resources/VideoResource.js @@ -1,8 +1,5 @@ import TextureResource from './TextureResource'; import * as ticker from '../../ticker'; -import { - uid -} from '../../utils'; export default class VideoResource extends TextureResource { @@ -34,7 +31,6 @@ source.addEventListener('play', this._onPlayStart.bind(this)); source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { source.addEventListener('canplay', this._onCanPlay); @@ -45,20 +41,20 @@ this._onCanPlay(); } - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { this.resolve = resolve; - if(this.loaded) + if (this.loaded) { this.resolve(this); } - }) + }); } update() { - //TODO - slow down and base on the videos framerate + // TODO - slow down and base on the videos framerate this.resourceUpdated.emit(); } @@ -127,7 +123,6 @@ */ _onCanPlay() { - if (this.source) { this.source.removeEventListener('canplay', this._onCanPlay); @@ -140,7 +135,7 @@ if (!this.loaded) { this.loaded = true; - if(this.resolve) + if (this.resolve) { this.resolve(this); } @@ -154,7 +149,6 @@ { this.source.play(); } - } } @@ -179,32 +173,6 @@ } /** - * Mimic Pixi BaseTexture.from.... method. - * - * @static - * @param {HTMLVideoElement} video - Video to create texture from - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - static fromVideo(video, scaleMode) - { - if (!video._pixiId) - { - video._pixiId = `video_${uid()}`; - } - - let baseTexture = BaseTextureCache[video._pixiId]; - - if (!baseTexture) - { - baseTexture = new VideoBaseTexture(video, scaleMode); - BaseTextureCache[video._pixiId] = baseTexture; - } - - return baseTexture; - } - - /** * Should the base texture automatically update itself, set to true by default * * @member {boolean} @@ -271,10 +239,8 @@ return new VideoResource(video, scaleMode); } - } - function createSource(path, type) { if (!type) diff --git a/src/core/textures/resources/createResource.js b/src/core/textures/resources/createResource.js index f3fa500..60fdba6 100644 --- a/src/core/textures/resources/createResource.js +++ b/src/core/textures/resources/createResource.js @@ -5,26 +5,24 @@ export default function createResource(source) { - if (typeof source === 'string') - { + if (typeof source === 'string') + { // check if its a video.. if (source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)) { - return new VideoResource.fromUrl(source); - //video! - //return Texture.fromVideoUrl(source); - //return SVGResource.from(url); + return new VideoResource.fromUrl(source); + // video! + // return Texture.fromVideoUrl(source); + // return SVGResource.from(url); } else if (source.match(/\.(svg)$/)) { // SVG return SVGResource.from(source); } - else - { + // probably an image! - return ImageResource.from(source); - } + return ImageResource.from(source); } else if (source instanceof HTMLImageElement) { @@ -38,8 +36,6 @@ { return new VideoResource(source); } - else - { - return source; - } -} \ No newline at end of file + + return source; +} diff --git a/src/core/utils/getTestContext.js b/src/core/utils/getTestContext.js index 288f12e..fd46ca4 100644 --- a/src/core/utils/getTestContext.js +++ b/src/core/utils/getTestContext.js @@ -1,8 +1,5 @@ - - let context = null; - /** * returns a little webGL context to use for program inspection. * @@ -13,7 +10,7 @@ export default function getTestContext() { - if(!context) + if (!context) { const canvas = document.createElement('canvas'); const options = {}; @@ -21,10 +18,9 @@ canvas.width = 1; canvas.height = 1; - - context = canvas.getContext('webgl2', options) || - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + context = canvas.getContext('webgl2', options) + || canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!context) { diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/TextureResource.js b/src/core/textures/resources/TextureResource.js index 6f73793..7516c1e 100644 --- a/src/core/textures/resources/TextureResource.js +++ b/src/core/textures/resources/TextureResource.js @@ -4,7 +4,7 @@ { constructor(source) { - this.source = source; + this.source = source; this.loaded = false; // TODO rename to ready? @@ -21,6 +21,6 @@ destroy() { - console.warn(this, ' has no destroy function') + // somthing } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/VideoResource.js b/src/core/textures/resources/VideoResource.js index 3402f96..1d6f5f8 100644 --- a/src/core/textures/resources/VideoResource.js +++ b/src/core/textures/resources/VideoResource.js @@ -1,8 +1,5 @@ import TextureResource from './TextureResource'; import * as ticker from '../../ticker'; -import { - uid -} from '../../utils'; export default class VideoResource extends TextureResource { @@ -34,7 +31,6 @@ source.addEventListener('play', this._onPlayStart.bind(this)); source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { source.addEventListener('canplay', this._onCanPlay); @@ -45,20 +41,20 @@ this._onCanPlay(); } - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { this.resolve = resolve; - if(this.loaded) + if (this.loaded) { this.resolve(this); } - }) + }); } update() { - //TODO - slow down and base on the videos framerate + // TODO - slow down and base on the videos framerate this.resourceUpdated.emit(); } @@ -127,7 +123,6 @@ */ _onCanPlay() { - if (this.source) { this.source.removeEventListener('canplay', this._onCanPlay); @@ -140,7 +135,7 @@ if (!this.loaded) { this.loaded = true; - if(this.resolve) + if (this.resolve) { this.resolve(this); } @@ -154,7 +149,6 @@ { this.source.play(); } - } } @@ -179,32 +173,6 @@ } /** - * Mimic Pixi BaseTexture.from.... method. - * - * @static - * @param {HTMLVideoElement} video - Video to create texture from - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - static fromVideo(video, scaleMode) - { - if (!video._pixiId) - { - video._pixiId = `video_${uid()}`; - } - - let baseTexture = BaseTextureCache[video._pixiId]; - - if (!baseTexture) - { - baseTexture = new VideoBaseTexture(video, scaleMode); - BaseTextureCache[video._pixiId] = baseTexture; - } - - return baseTexture; - } - - /** * Should the base texture automatically update itself, set to true by default * * @member {boolean} @@ -271,10 +239,8 @@ return new VideoResource(video, scaleMode); } - } - function createSource(path, type) { if (!type) diff --git a/src/core/textures/resources/createResource.js b/src/core/textures/resources/createResource.js index f3fa500..60fdba6 100644 --- a/src/core/textures/resources/createResource.js +++ b/src/core/textures/resources/createResource.js @@ -5,26 +5,24 @@ export default function createResource(source) { - if (typeof source === 'string') - { + if (typeof source === 'string') + { // check if its a video.. if (source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)) { - return new VideoResource.fromUrl(source); - //video! - //return Texture.fromVideoUrl(source); - //return SVGResource.from(url); + return new VideoResource.fromUrl(source); + // video! + // return Texture.fromVideoUrl(source); + // return SVGResource.from(url); } else if (source.match(/\.(svg)$/)) { // SVG return SVGResource.from(source); } - else - { + // probably an image! - return ImageResource.from(source); - } + return ImageResource.from(source); } else if (source instanceof HTMLImageElement) { @@ -38,8 +36,6 @@ { return new VideoResource(source); } - else - { - return source; - } -} \ No newline at end of file + + return source; +} diff --git a/src/core/utils/getTestContext.js b/src/core/utils/getTestContext.js index 288f12e..fd46ca4 100644 --- a/src/core/utils/getTestContext.js +++ b/src/core/utils/getTestContext.js @@ -1,8 +1,5 @@ - - let context = null; - /** * returns a little webGL context to use for program inspection. * @@ -13,7 +10,7 @@ export default function getTestContext() { - if(!context) + if (!context) { const canvas = document.createElement('canvas'); const options = {}; @@ -21,10 +18,9 @@ canvas.width = 1; canvas.height = 1; - - context = canvas.getContext('webgl2', options) || - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + context = canvas.getContext('webgl2', options) + || canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!context) { diff --git a/src/extras/webgl/TilingSpriteRenderer.js b/src/extras/webgl/TilingSpriteRenderer.js index eee3b5c..3743b62 100644 --- a/src/extras/webgl/TilingSpriteRenderer.js +++ b/src/extras/webgl/TilingSpriteRenderer.js @@ -1,6 +1,5 @@ import * as core from '../../core'; import { WRAP_MODES } from '../../core/const'; -import { GLShader } from 'pixi-gl-core'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -26,7 +25,7 @@ { super(renderer); - const uniforms = {globals:this.renderer.globalUniforms}; + const uniforms = { globals: this.renderer.globalUniforms }; this.shader = new core.Shader.from( readFileSync(join(__dirname, './tilingSprite.vert'), 'utf8'), @@ -69,8 +68,6 @@ vertices[5] = vertices[7] = 1.0 - ts.anchor.y; } - // quad.upload(); - const tex = ts._texture; const baseTex = tex.baseTexture; const lt = ts.tileTransform.localTransform; @@ -96,7 +93,6 @@ const shader = isSimple ? this.simpleShader : this.shader; - const w = tex.width; const h = tex.height; const W = ts._width; @@ -135,7 +131,7 @@ color[3] = ts.worldAlpha; shader.uniforms.uColor = color; shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - shader.uniforms.uSampler = tex;//renderer.texture.bind(tex.baseTexture, 0); + shader.uniforms.uSampler = tex; renderer.shader.bind(shader); renderer.geometry.bind(quad, renderer.shader.getGLShader()); diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/TextureResource.js b/src/core/textures/resources/TextureResource.js index 6f73793..7516c1e 100644 --- a/src/core/textures/resources/TextureResource.js +++ b/src/core/textures/resources/TextureResource.js @@ -4,7 +4,7 @@ { constructor(source) { - this.source = source; + this.source = source; this.loaded = false; // TODO rename to ready? @@ -21,6 +21,6 @@ destroy() { - console.warn(this, ' has no destroy function') + // somthing } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/VideoResource.js b/src/core/textures/resources/VideoResource.js index 3402f96..1d6f5f8 100644 --- a/src/core/textures/resources/VideoResource.js +++ b/src/core/textures/resources/VideoResource.js @@ -1,8 +1,5 @@ import TextureResource from './TextureResource'; import * as ticker from '../../ticker'; -import { - uid -} from '../../utils'; export default class VideoResource extends TextureResource { @@ -34,7 +31,6 @@ source.addEventListener('play', this._onPlayStart.bind(this)); source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { source.addEventListener('canplay', this._onCanPlay); @@ -45,20 +41,20 @@ this._onCanPlay(); } - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { this.resolve = resolve; - if(this.loaded) + if (this.loaded) { this.resolve(this); } - }) + }); } update() { - //TODO - slow down and base on the videos framerate + // TODO - slow down and base on the videos framerate this.resourceUpdated.emit(); } @@ -127,7 +123,6 @@ */ _onCanPlay() { - if (this.source) { this.source.removeEventListener('canplay', this._onCanPlay); @@ -140,7 +135,7 @@ if (!this.loaded) { this.loaded = true; - if(this.resolve) + if (this.resolve) { this.resolve(this); } @@ -154,7 +149,6 @@ { this.source.play(); } - } } @@ -179,32 +173,6 @@ } /** - * Mimic Pixi BaseTexture.from.... method. - * - * @static - * @param {HTMLVideoElement} video - Video to create texture from - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - static fromVideo(video, scaleMode) - { - if (!video._pixiId) - { - video._pixiId = `video_${uid()}`; - } - - let baseTexture = BaseTextureCache[video._pixiId]; - - if (!baseTexture) - { - baseTexture = new VideoBaseTexture(video, scaleMode); - BaseTextureCache[video._pixiId] = baseTexture; - } - - return baseTexture; - } - - /** * Should the base texture automatically update itself, set to true by default * * @member {boolean} @@ -271,10 +239,8 @@ return new VideoResource(video, scaleMode); } - } - function createSource(path, type) { if (!type) diff --git a/src/core/textures/resources/createResource.js b/src/core/textures/resources/createResource.js index f3fa500..60fdba6 100644 --- a/src/core/textures/resources/createResource.js +++ b/src/core/textures/resources/createResource.js @@ -5,26 +5,24 @@ export default function createResource(source) { - if (typeof source === 'string') - { + if (typeof source === 'string') + { // check if its a video.. if (source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)) { - return new VideoResource.fromUrl(source); - //video! - //return Texture.fromVideoUrl(source); - //return SVGResource.from(url); + return new VideoResource.fromUrl(source); + // video! + // return Texture.fromVideoUrl(source); + // return SVGResource.from(url); } else if (source.match(/\.(svg)$/)) { // SVG return SVGResource.from(source); } - else - { + // probably an image! - return ImageResource.from(source); - } + return ImageResource.from(source); } else if (source instanceof HTMLImageElement) { @@ -38,8 +36,6 @@ { return new VideoResource(source); } - else - { - return source; - } -} \ No newline at end of file + + return source; +} diff --git a/src/core/utils/getTestContext.js b/src/core/utils/getTestContext.js index 288f12e..fd46ca4 100644 --- a/src/core/utils/getTestContext.js +++ b/src/core/utils/getTestContext.js @@ -1,8 +1,5 @@ - - let context = null; - /** * returns a little webGL context to use for program inspection. * @@ -13,7 +10,7 @@ export default function getTestContext() { - if(!context) + if (!context) { const canvas = document.createElement('canvas'); const options = {}; @@ -21,10 +18,9 @@ canvas.width = 1; canvas.height = 1; - - context = canvas.getContext('webgl2', options) || - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + context = canvas.getContext('webgl2', options) + || canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!context) { diff --git a/src/extras/webgl/TilingSpriteRenderer.js b/src/extras/webgl/TilingSpriteRenderer.js index eee3b5c..3743b62 100644 --- a/src/extras/webgl/TilingSpriteRenderer.js +++ b/src/extras/webgl/TilingSpriteRenderer.js @@ -1,6 +1,5 @@ import * as core from '../../core'; import { WRAP_MODES } from '../../core/const'; -import { GLShader } from 'pixi-gl-core'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -26,7 +25,7 @@ { super(renderer); - const uniforms = {globals:this.renderer.globalUniforms}; + const uniforms = { globals: this.renderer.globalUniforms }; this.shader = new core.Shader.from( readFileSync(join(__dirname, './tilingSprite.vert'), 'utf8'), @@ -69,8 +68,6 @@ vertices[5] = vertices[7] = 1.0 - ts.anchor.y; } - // quad.upload(); - const tex = ts._texture; const baseTex = tex.baseTexture; const lt = ts.tileTransform.localTransform; @@ -96,7 +93,6 @@ const shader = isSimple ? this.simpleShader : this.shader; - const w = tex.width; const h = tex.height; const W = ts._width; @@ -135,7 +131,7 @@ color[3] = ts.worldAlpha; shader.uniforms.uColor = color; shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - shader.uniforms.uSampler = tex;//renderer.texture.bind(tex.baseTexture, 0); + shader.uniforms.uSampler = tex; renderer.shader.bind(shader); renderer.geometry.bind(quad, renderer.shader.getGLShader()); diff --git a/src/mesh/webgl/MeshRenderer.js b/src/mesh/webgl/MeshRenderer.js index 1089c3c..2b78908 100644 --- a/src/mesh/webgl/MeshRenderer.js +++ b/src/mesh/webgl/MeshRenderer.js @@ -1,9 +1,5 @@ import * as core from '../../core'; -const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; - -const matrixIdentity = core.Matrix.IDENTITY; - /** * WebGL renderer plugin for tiling sprites * @@ -67,16 +63,6 @@ // then render it this.renderer.geometry.draw(mesh.drawMode, mesh.size, mesh.start, mesh.geometry.instanceCount); } - - - /** - * draws mesh - * @param {PIXI.mesh.RawMesh} mesh mesh instance - */ - draw(mesh) - { - mesh.geometry.glVertexArrayObjects[this.CONTEXT_UID].draw(mesh.drawMode, mesh.size, mesh.start, mesh.geometry.instanceCount); - } } core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); diff --git a/.eslintrc.json b/.eslintrc.json index cb6c09d..7948d3c 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -19,7 +19,7 @@ // Possible Errors "comma-dangle": [1, "always-multiline"], "no-cond-assign": [1, "except-parens"], - "no-console": 1, + "no-console": [1, { "allow": ["warn", "error"] }], "no-constant-condition": 1, "no-control-regex": 1, "no-debugger": 1, @@ -45,7 +45,7 @@ "no-unreachable": 1, "no-unsafe-finally": 1, "use-isnan": 1, - "valid-jsdoc": [1, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], + "valid-jsdoc": [0, { "requireReturn": false, "requireReturnType": true, "requireParamDescription": true, "requireReturnDescription": true }], "valid-typeof": 1, // Best Practices @@ -205,7 +205,7 @@ "padded-blocks": [1, "never"], "quote-props": [1, "as-needed"], "quotes": [1, "single", { "allowTemplateLiterals": true }], - "require-jsdoc": [1, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], + "require-jsdoc": [0, { "require": { "FunctionDeclaration": false, "ClassDeclaration": true, "MethodDefinition": true } }], "semi": [1, "always"], "semi-spacing": [1, { "before": false, "after": true }], "sort-vars": 0, diff --git a/src/core/const.js b/src/core/const.js index f10cc4b..7e4e787 100644 --- a/src/core/const.js +++ b/src/core/const.js @@ -145,26 +145,26 @@ }; export const TARGETS = { - TEXTURE_2D:3553, - TEXTURE_CUBE_MAP:34067, - TEXTURE_2D_ARRAY:35866, - TEXTURE_CUBE_MAP_POSITIVE_X:34069, - TEXTURE_CUBE_MAP_NEGATIVE_X:34070, - TEXTURE_CUBE_MAP_POSITIVE_Y:34071, - TEXTURE_CUBE_MAP_NEGATIVE_Y:34072, - TEXTURE_CUBE_MAP_POSITIVE_Z:34073, - TEXTURE_CUBE_MAP_NEGATIVE_Z:34074, + TEXTURE_2D: 3553, + TEXTURE_CUBE_MAP: 34067, + TEXTURE_2D_ARRAY: 35866, + TEXTURE_CUBE_MAP_POSITIVE_X: 34069, + TEXTURE_CUBE_MAP_NEGATIVE_X: 34070, + TEXTURE_CUBE_MAP_POSITIVE_Y: 34071, + TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072, + TEXTURE_CUBE_MAP_POSITIVE_Z: 34073, + TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074, }; export const TYPES = { - UNSIGNED_BYTE:5121, + UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123, - UNSIGNED_SHORT_5_6_5:33635, - UNSIGNED_SHORT_4_4_4_4:32819, - UNSIGNED_SHORT_5_5_5_1:32820, - FLOAT:5126, - HALF_FLOAT:36193, -} + UNSIGNED_SHORT_5_6_5: 33635, + UNSIGNED_SHORT_4_4_4_4: 32819, + UNSIGNED_SHORT_5_5_5_1: 32820, + FLOAT: 5126, + HALF_FLOAT: 36193, +}; /** * The scale modes that are supported by pixi. diff --git a/src/core/display/Container.js b/src/core/display/Container.js index f99168d..9b7930c 100644 --- a/src/core/display/Container.js +++ b/src/core/display/Container.js @@ -449,7 +449,7 @@ if (this._enabledFilters.length) { - renderer.filterManager.pushFilter(this, this._enabledFilters); + renderer.filter.push(this, this._enabledFilters); } } @@ -476,7 +476,7 @@ if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filterManager.popFilter(); + renderer.filter.pop(); } } diff --git a/src/core/geometry/Geometry.js b/src/core/geometry/Geometry.js index c8ed986..eaa2150 100644 --- a/src/core/geometry/Geometry.js +++ b/src/core/geometry/Geometry.js @@ -62,6 +62,8 @@ this.instanced = false; + this.instanceCount = 1; + this._size = null; } @@ -122,7 +124,7 @@ // assuming that if there is instanced data then this will be drawn with instancing! this.instanced = this.instanced || instance; - this._si + return this; } @@ -231,17 +233,16 @@ getSize() { - for (var i in this.attributes) + for (const i in this.attributes) { const attribute = this.attributes[i]; const buffer = this.buffers[attribute.buffer]; - return buffer.data.length / (( attribute.stride/4 ) || attribute.size); + return buffer.data.length / ((attribute.stride / 4) || attribute.size); } return 0; - }; - + } /** * Destroys the geometry. diff --git a/src/core/graphics/webgl/GraphicsRenderer.js b/src/core/graphics/webgl/GraphicsRenderer.js index 4de266d..01382e8 100644 --- a/src/core/graphics/webgl/GraphicsRenderer.js +++ b/src/core/graphics/webgl/GraphicsRenderer.js @@ -2,8 +2,6 @@ import { SHAPES } from '../../const'; import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import Geometry from '../../geometry/Geometry'; -import Buffer from '../../geometry/Buffer'; import WebGLGraphicsData from './WebGLGraphicsData'; import PrimitiveShader from './shaders/PrimitiveShader'; @@ -31,7 +29,7 @@ this.graphicsDataPool = []; this.primitiveShader = new PrimitiveShader(); - this.primitiveShader.uniforms.globals = renderer.globalUniforms + this.primitiveShader.uniforms.globals = renderer.globalUniforms; this.gl = renderer.gl; // easy access! @@ -100,11 +98,11 @@ shader.uniforms.alpha = graphics.worldAlpha; renderer.shader.bind(shader); - renderer.geometry.bind(webGLData.geometry, renderer.shader.getGLShader()); + renderer.geometry.bind(webGLData.geometry); if (graphics.nativeLines) { - renderer.geometry.draw(gl.LINES, webGLData.indices.length/6); + renderer.geometry.draw(gl.LINES, webGLData.indices.length / 6); } else { @@ -183,7 +181,7 @@ webGL.lastIndex++; } - //this.renderer.geometry.bindVao(null); + // this.renderer.geometry.bindVao(null); // upload all the dirty data... for (let i = 0; i < webGL.data.length; i++) @@ -210,7 +208,11 @@ if (!webGLData || webGLData.points.length > 320000) { - webGLData = this.graphicsDataPool.pop() || new WebGLGraphicsData(this.renderer.gl, this.primitiveShader, this.renderer.state.attribsState); + webGLData = this.graphicsDataPool.pop() + || new WebGLGraphicsData(this.renderer.gl, + this.primitiveShader, + this.renderer.state.attribsState); + webGLData.reset(type); gl.data.push(webGLData); } diff --git a/src/core/graphics/webgl/WebGLGraphicsData.js b/src/core/graphics/webgl/WebGLGraphicsData.js index 03c4384..04d4679 100644 --- a/src/core/graphics/webgl/WebGLGraphicsData.js +++ b/src/core/graphics/webgl/WebGLGraphicsData.js @@ -13,9 +13,8 @@ /** * @param {WebGLRenderingContext} gl - The current WebGL drawing context * @param {PIXI.Shader} shader - The shader - * @param {object} attribsState - The state for the VAO */ - constructor(gl, shader, attribsState) + constructor(gl, shader) { /** * The current WebGL drawing context @@ -60,7 +59,6 @@ */ this.dirty = true; - /** * * @member {PIXI.Shader} @@ -77,7 +75,6 @@ */ reset() { - this.points.length = 0; this.indices.length = 0; } diff --git a/src/core/graphics/webgl/shaders/PrimitiveShader.js b/src/core/graphics/webgl/shaders/PrimitiveShader.js index d2c4156..37003b1 100644 --- a/src/core/graphics/webgl/shaders/PrimitiveShader.js +++ b/src/core/graphics/webgl/shaders/PrimitiveShader.js @@ -1,6 +1,5 @@ import Shader from '../../../shader/Shader'; import Program from '../../../shader/Program'; -import { PRECISION } from '../../../const'; /** * This shader is used to draw simple primitive shapes for {@link PIXI.Graphics}. @@ -17,22 +16,22 @@ constructor() { const program = Program.from([ - 'attribute vec2 aVertexPosition;', - 'attribute vec4 aColor;', + 'attribute vec2 aVertexPosition;', + 'attribute vec4 aColor;', - 'uniform mat3 translationMatrix;', - 'uniform mat3 projectionMatrix;', + 'uniform mat3 translationMatrix;', + 'uniform mat3 projectionMatrix;', - 'uniform float alpha;', - 'uniform vec3 tint;', + 'uniform float alpha;', + 'uniform vec3 tint;', - 'varying vec4 vColor;', + 'varying vec4 vColor;', - 'void main(void){', - ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', - ' vColor = aColor * vec4(tint * alpha, alpha);', - '}', - ].join('\n'), + 'void main(void){', + ' gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);', + ' vColor = aColor * vec4(tint * alpha, alpha);', + '}', + ].join('\n'), // fragment shader [ 'varying vec4 vColor;', @@ -42,6 +41,6 @@ '}', ].join('\n')); - super(program, {}) + super(program, {}); } } diff --git a/src/core/renderers/SystemRenderer.js b/src/core/renderers/SystemRenderer.js index 18c0a9d..d379539 100644 --- a/src/core/renderers/SystemRenderer.js +++ b/src/core/renderers/SystemRenderer.js @@ -1,4 +1,4 @@ -import { sayHello, hex2string, hex2rgb } from '../utils'; +import { hex2string, hex2rgb } from '../utils'; import { Matrix, Rectangle } from '../math'; import { RENDERER_TYPE } from '../const'; import settings from '../settings'; @@ -42,8 +42,6 @@ { super(); - - // Support for constructor(system, screenWidth, screenHeight, options) if (typeof options === 'number') { diff --git a/src/core/renderers/webgl/WebGLRenderer.js b/src/core/renderers/webgl/WebGLRenderer.js index dc83e69..50e7b4d 100644 --- a/src/core/renderers/webgl/WebGLRenderer.js +++ b/src/core/renderers/webgl/WebGLRenderer.js @@ -1,5 +1,5 @@ import SystemRenderer from '../SystemRenderer'; -import { sayHello } from '../../utils'; +import { sayHello, pluginTarget } from '../../utils'; import MaskSystem from './systems/MaskSystem'; import StencilSystem from './systems/StencilSystem'; import FilterSystem from './systems/FilterSystem'; @@ -12,12 +12,10 @@ import ShaderSystem from './systems/shader/ShaderSystem'; import ContextSystem from './systems/ContextSystem'; import BatchSystem from './systems/BatchSystem'; -import TextureGCSystem from './systems/textures/TextureGCSystem'; -import { pluginTarget } from '../../utils'; -import VertexArrayObject from './systems/geometry/VertexArrayObject'; +// import TextureGCSystem from './systems/textures/TextureGCSystem'; import { RENDERER_TYPE } from '../../const'; import UniformGroup from '../../shader/UniformGroup'; -import { Rectangle, Matrix } from '../../math'; +import { Matrix } from '../../math'; import Runner from 'mini-runner'; /** @@ -74,10 +72,7 @@ this.CONTEXT_UID = 0; this.legacy = !!options.legacy; - if (this.legacy) - { - VertexArrayObject.FORCE_NATIVE = true; - } + // TODO legacy! // runners! this.runners = { @@ -90,12 +85,11 @@ resize: new Runner('resize', 2), }; - this._backgroundColorRgba[3] = this.transparent ? 0 : 1; this.globalUniforms = new UniformGroup({ - projectionMatrix:new Matrix(), - }, true) + projectionMatrix: new Matrix(), + }, true); this.addSystem(MaskSystem, 'mask') .addSystem(ContextSystem, 'context') @@ -106,21 +100,20 @@ .addSystem(FramebufferSystem, 'framebuffer') .addSystem(StencilSystem, 'stencil') .addSystem(ProjectionSystem, 'projection') - //.addSystem(TextureGCSystem) + // .addSystem(TextureGCSystem) .addSystem(FilterSystem, 'filter') .addSystem(RenderTextureSystem, 'renderTexture') - .addSystem(BatchSystem,'batch') + .addSystem(BatchSystem, 'batch'); this.initPlugins(); - /** * The options passed in to create a new webgl context. * * @member {object} * @private */ - if(options.context) + if (options.context) { this.context.initFromContext(options.context); } @@ -144,12 +137,12 @@ addSystem(_class, name) { - if(!name) + if (!name) { name = _class.name; } - //TODO - read name from class.name.. + // TODO - read name from class.name.. /* if(name.includes('System')) @@ -161,15 +154,14 @@ const system = new _class(this); - if(this[name]) + if (this[name]) { - throw new Error('Whoops! ' + name + ' is already a manger'); - return; + throw new Error(`Whoops! ${name} is already a manger`); } this[name] = system; - for(var i in this.runners) + for (const i in this.runners) { this.runners[i].add(system); } @@ -239,7 +231,7 @@ this.emit('prerender'); // no point rendering if our context has been blown up! - if(this.context.isLost) + if (this.context.isLost) { return; } @@ -297,6 +289,7 @@ reset() { this.runners.reset.run(); + return this; } diff --git a/src/core/renderers/webgl/systems/BatchSystem.js b/src/core/renderers/webgl/systems/BatchSystem.js index a01cc0b..d260ec9 100644 --- a/src/core/renderers/webgl/systems/BatchSystem.js +++ b/src/core/renderers/webgl/systems/BatchSystem.js @@ -1,6 +1,5 @@ import WebGLSystem from './WebGLSystem'; import ObjectRenderer from '../utils/ObjectRenderer'; -import { Rectangle, Matrix } from '../../../math'; /** * @class @@ -64,6 +63,6 @@ reset() { - this.setObjectRenderer(this.emptyRenderer); + this.setObjectRenderer(this.emptyRenderer); } } diff --git a/src/core/renderers/webgl/systems/ContextSystem.js b/src/core/renderers/webgl/systems/ContextSystem.js index 16b3822..7430d11 100644 --- a/src/core/renderers/webgl/systems/ContextSystem.js +++ b/src/core/renderers/webgl/systems/ContextSystem.js @@ -1,5 +1,4 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; let CONTEXT_UID = 0; @@ -8,7 +7,6 @@ * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class ContextSystem extends WebGLSystem { /** @@ -25,44 +23,38 @@ renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); - } get isLost() { - return (!this.gl || this.gl.isContextLost()); + return (!this.gl || this.gl.isContextLost()); } contextChange(gl) { - this.gl = gl; + this.gl = gl; // restore a context if it was previously lost if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { gl.getExtension('WEBGL_lose_context').restoreContext(); } - - // setup the width/height properties and gl viewport - //this.resize(this.screen.width, this.screen.height); - // const renderer = this.renderer; - - // renderer.resize(renderer.screen.width, renderer.screen.height); } initFromContext(gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID++; - this.renderer.runners.contextChange.run(gl); + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID++; + this.renderer.runners.contextChange.run(gl); } initFromOptions(options) { - const gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); + const gl = this.createContext(this.renderer.view, options); + + this.initFromContext(gl); } /** @@ -72,14 +64,14 @@ * @memberof PIXI.glCore * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from * @param options {Object} An options object that gets passed in to the canvas element containing the context attributes, - * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available + * see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext for the options available * @return {WebGLRenderingContext} the WebGL context */ createContext(canvas, options) { - var gl = canvas.getContext('webgl2', options); + let gl = canvas.getContext('webgl2', options); - if(gl) + if (gl) { this.webGLversion = 2; } @@ -87,8 +79,8 @@ { this.webGLversion = 1; - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + gl = canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!gl) { @@ -98,7 +90,7 @@ } return gl; - }; + } /** * Handles a lost webgl context @@ -118,17 +110,14 @@ */ handleContextRestored() { - this.renderer.runners.contextChange.run(gl); - - // TODO - tidy up textures? - //this.textureSystem.removeAll(); + this.renderer.runners.contextChange.run(this.gl); } destroy() { - const view = this.renderer.view; + const view = this.renderer.view; - // remove listeners + // remove listeners view.removeEventListener('webglcontextlost', this.handleContextLost); view.removeEventListener('webglcontextrestored', this.handleContextRestored); @@ -138,12 +127,11 @@ { this.gl.getExtension('WEBGL_lose_context').loseContext(); } - } postrender() { - this.gl.flush(); + this.gl.flush(); } validateContext(gl) @@ -153,9 +141,13 @@ // this is going to be fairly simple for now.. but at least we have room to grow! if (!attributes.stencil) { + /* eslint-disable max-len */ + /* eslint-disable no-console */ console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); /* eslint-enable no-console */ + + /* eslint-enable max-len */ } } } diff --git a/src/core/renderers/webgl/systems/FilterSystem.js b/src/core/renderers/webgl/systems/FilterSystem.js index 37e28d2..7c5ed2c 100644 --- a/src/core/renderers/webgl/systems/FilterSystem.js +++ b/src/core/renderers/webgl/systems/FilterSystem.js @@ -2,7 +2,7 @@ import RenderTarget from '../utils/RenderTarget'; import Quad from '../utils/Quad'; import { Rectangle } from '../../../math'; -//import Shader from '../../../Shader'; +import Shader from '../../../shader/Shader'; import * as filterTransforms from '../filters/filterTransforms'; import bitTwiddle from 'bit-twiddle'; @@ -40,7 +40,6 @@ { super(renderer); - this.shaderCache = {}; // todo add default! this.pool = {}; @@ -53,7 +52,6 @@ this.gl = this.renderer.gl; // know about sprites! this.quad = new Quad(this.gl, this.renderer.state.attribState); - } /** @@ -62,7 +60,7 @@ * @param {PIXI.DisplayObject} target - The target of the filter to render. * @param {PIXI.Filter[]} filters - The filters to apply. */ - pushFilter(target, filters) + push(target, filters) { const renderer = this.renderer; @@ -70,7 +68,7 @@ if (!filterData) { - filterData = this.renderer._activeRenderTarget.filterStack; + filterData = this.renderer.renderTexture.current.filterStack; // add new stack const filterState = new FilterState(); @@ -146,7 +144,7 @@ * Pops off the filter and applies it. * */ - popFilter() + pop() { const filterData = this.filterData; diff --git a/src/core/renderers/webgl/systems/FramebufferSystem.js b/src/core/renderers/webgl/systems/FramebufferSystem.js index 38eaa56..214f5b1 100644 --- a/src/core/renderers/webgl/systems/FramebufferSystem.js +++ b/src/core/renderers/webgl/systems/FramebufferSystem.js @@ -8,14 +8,6 @@ export default class FramebufferSystem extends WebGLSystem { /** - * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. - */ - constructor(renderer) - { - super(renderer); - } - - /** * Sets up the renderer context and necessary buffers. * * @private @@ -28,68 +20,66 @@ this.drawBufferExtension = this.gl.getExtension('WEBGL_draw_buffers'); } - // public API - bind(framebuffer) { const gl = this.gl; - if(framebuffer) + if (framebuffer) { // TODO cacheing layer! const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); // makesure all textures are unbound.. // now check for updates... - if(fbo.dirtyId !== framebuffer.dirtyId) + if (fbo.dirtyId !== framebuffer.dirtyId) { fbo.dirtyId = framebuffer.dirtyId; - if(fbo.dirtyFormat !== framebuffer.dirtyFormat) + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { fbo.dirtyFormat = framebuffer.dirtyFormat; this.updateFramebuffer(framebuffer); } - else if(fbo.dirtySize !== framebuffer.dirtySize) + else if (fbo.dirtySize !== framebuffer.dirtySize) { fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer) + this.resizeFramebuffer(framebuffer); } } - for (var i = 0; i < framebuffer.colorTextures.length; i++) + for (let i = 0; i < framebuffer.colorTextures.length; i++) { - if(framebuffer.colorTextures[i].texturePart) + if (framebuffer.colorTextures[i].texturePart) { - this.renderer.texture.unbind(framebuffer.colorTextures[i].texture) + this.renderer.texture.unbind(framebuffer.colorTextures[i].texture); } else { - this.renderer.texture.unbind(framebuffer.colorTextures[i]) + this.renderer.texture.unbind(framebuffer.colorTextures[i]); } } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { this.renderer.texture.unbind(framebuffer.depthTexture); } - gl.viewport(0,0,framebuffer.width, framebuffer.height); - + gl.viewport(0, 0, framebuffer.width, framebuffer.height); } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); - gl.viewport(0,0,this.renderer.width, this.renderer.height); + gl.viewport(0, 0, this.renderer.width, this.renderer.height); } } clear(r, g, b, a) { - var gl = this.gl; + const gl = this.gl; // TODO clear color can be set only one right? gl.clearColor(r, g, b, a); @@ -103,13 +93,13 @@ const gl = this.gl; // TODO - make this a class? - var fbo = { - framebuffer:gl.createFramebuffer(), - stencil:null, - dirtyId:0, - dirtyFormat:0, - dirtySize:0, - } + const fbo = { + framebuffer: gl.createFramebuffer(), + stencil: null, + dirtyId: 0, + dirtyFormat: 0, + dirtySize: 0, + }; framebuffer.glFrameBuffers[this.CONTEXT_UID] = fbo; @@ -119,9 +109,8 @@ resizeFramebuffer(framebuffer) { const gl = this.gl; - const fbo = framebuffer.glFrameBuffers[this.CONTEXT_UID]; - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { gl.bindRenderbuffer(gl.RENDERBUFFER, this.stencil); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); @@ -139,18 +128,18 @@ let count = colorTextures.length; - if(!this.drawBufferExtension) + if (!this.drawBufferExtension) { count = Math.min(count, 1); } const activeTextures = []; - for (var i = 0; i < count; i++) + for (let i = 0; i < count; i++) { - let texture = framebuffer.colorTextures[i]; + const texture = framebuffer.colorTextures[i]; - if(texture.texturePart) + if (texture.texturePart) { this.renderer.texture.bind(texture.texture, 0); @@ -174,18 +163,18 @@ activeTextures.push(gl.COLOR_ATTACHMENT0 + i); } - if(this.drawBufferExtension && activeTextures.length > 1) + if (this.drawBufferExtension && activeTextures.length > 1) { this.drawBufferExtension.drawBuffersWEBGL(activeTextures); } - if(framebuffer.depthTexture) + if (framebuffer.depthTexture) { - var depthTextureExt = gl.getExtension("WEBKIT_WEBGL_depth_texture"); + const depthTextureExt = gl.getExtension('WEBKIT_WEBGL_depth_texture'); - if(depthTextureExt) + if (depthTextureExt) { - let depthTexture = framebuffer.depthTexture; + const depthTexture = framebuffer.depthTexture; this.renderer.texture.bind(depthTexture, 0); @@ -197,7 +186,7 @@ } } - if(framebuffer.stencil || framebuffer.depth) + if (framebuffer.stencil || framebuffer.depth) { fbo.stencil = gl.createRenderbuffer(); @@ -205,9 +194,9 @@ // TODO.. this is depth AND stencil? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width , framebuffer.height ); - //fbo.enableStencil(); + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + // fbo.enableStencil(); } } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/systems/ProjectionSystem.js b/src/core/renderers/webgl/systems/ProjectionSystem.js index d8cb662..602e3d5 100644 --- a/src/core/renderers/webgl/systems/ProjectionSystem.js +++ b/src/core/renderers/webgl/systems/ProjectionSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Matrix } from '../../../math'; /** * @class @@ -50,7 +50,6 @@ pm.tx = -1 - (sourceFrame.x * pm.a); pm.ty = -1 - (sourceFrame.y * pm.d); - } else { @@ -63,17 +62,16 @@ // apply the resolution.. // TODO - prob should apply this to x and y too! - pm.a *= resolution; - pm.d *= resolution; + pm.a *= resolution; + pm.d *= resolution; } - /** * Sets the transform of the active render target to the given matrix * * @param {PIXI.Matrix} matrix - The transformation matrix */ - setTransform(matrix) + setTransform()// matrix) { // this._activeRenderTarget.transform = matrix; } diff --git a/src/core/renderers/webgl/systems/RenderTextureSystem.js b/src/core/renderers/webgl/systems/RenderTextureSystem.js index e37d086..a8c737a 100644 --- a/src/core/renderers/webgl/systems/RenderTextureSystem.js +++ b/src/core/renderers/webgl/systems/RenderTextureSystem.js @@ -1,5 +1,5 @@ import WebGLSystem from './WebGLSystem'; -import { Rectangle, Matrix } from '../../../math'; +import { Rectangle } from '../../../math'; const tempRect = new Rectangle(); @@ -22,24 +22,26 @@ // TODO moe this property somewhere else! this.defaultMaskStack = []; + + // empty render texture? } bind(renderTexture) { // TODO - do we want this?? - if(this.renderTexture === renderTexture)return; + if (this.renderTexture === renderTexture) return; this.renderTexture = renderTexture; + this.current = renderTexture; const renderer = this.renderer; - if(renderTexture) + if (renderTexture) { const baseTexture = renderTexture.baseTexture; - this.renderer.framebuffer.bind(baseRenderTexture.frameBuffer); - this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseRenderTexture.resolution, false); + this.renderer.framebuffer.bind(baseTexture.frameBuffer); + this.renderer.projection.update(renderTexture.frame, renderTexture.frame, baseTexture.resolution, false); this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack); - } else { @@ -47,17 +49,11 @@ tempRect.width = renderer.width; tempRect.height = renderer.height; + // TODO store this.. this.renderer.projection.update(tempRect, tempRect, this.renderer.resolution, true); this.renderer.stencil.setMaskStack(this.defaultMaskStack); } - - const glShader = renderer.shader.getGLShader() - - if (glShader) - { - // glShader.uniforms.projectionMatrix = this.renderer.projection.projectionMatrix.toArray(true); - } } /** @@ -68,7 +64,7 @@ */ clear(clearColor) { - if(this.renderTexture) + if (this.renderTexture) { clearColor = clearColor || this.renderTexture.baseTexture.clearColor; } @@ -80,9 +76,9 @@ this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]); } - resize(screenWidth, screenHeight) + resize()// screenWidth, screenHeight) { // resize the root only! - this.bind(null) + this.bind(null); } } diff --git a/src/core/renderers/webgl/systems/StateSystem.js b/src/core/renderers/webgl/systems/StateSystem.js index be6c69b..54c158a 100755 --- a/src/core/renderers/webgl/systems/StateSystem.js +++ b/src/core/renderers/webgl/systems/StateSystem.js @@ -50,8 +50,6 @@ this.defaultState = new WebGLState(); this.defaultState.blend = true; this.defaultState.depth = true; - - } contextChange(gl) diff --git a/src/core/renderers/webgl/systems/StencilSystem.js b/src/core/renderers/webgl/systems/StencilSystem.js index b04d71b..81954b1 100644 --- a/src/core/renderers/webgl/systems/StencilSystem.js +++ b/src/core/renderers/webgl/systems/StencilSystem.js @@ -21,7 +21,7 @@ * * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack */ - setMaskStack(stencilMaskStack) + setMaskStack(stencilMaskStack) { this.stencilMaskStack = stencilMaskStack; diff --git a/src/core/renderers/webgl/systems/geometry/GLBuffer.js b/src/core/renderers/webgl/systems/geometry/GLBuffer.js deleted file mode 100644 index 876b29e..0000000 --- a/src/core/renderers/webgl/systems/geometry/GLBuffer.js +++ /dev/null @@ -1,119 +0,0 @@ -var EMPTY_ARRAY_BUFFER = new ArrayBuffer(0); - -/** - * Helper class to create a webGL buffer - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - * @param type {gl.ARRAY_BUFFER | gl.ELEMENT_ARRAY_BUFFER} @mat - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data - * @param drawType {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ -var Buffer = function(gl, type, data, drawType) -{ - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * The WebGL buffer, created upon instantiation - * - * @member {WebGLBuffer} - */ - this.buffer = gl.createBuffer(); - - /** - * The type of the buffer - * - * @member {gl.ARRAY_BUFFER|gl.ELEMENT_ARRAY_BUFFER} - */ - this.type = type || gl.ARRAY_BUFFER; - - /** - * The draw type of the buffer - * - * @member {gl.STATIC_DRAW|gl.DYNAMIC_DRAW|gl.STREAM_DRAW} - */ - this.drawType = drawType || gl.STATIC_DRAW; - - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} - */ - this.data = EMPTY_ARRAY_BUFFER; - - if(data) - { - this.upload(data); - } - - this._updateID = 0; -}; - -/** - * Uploads the buffer to the GPU - * @param data {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} an array of data to upload - * @param offset {Number} if only a subset of the data should be uploaded, this is the amount of data to subtract - * @param dontBind {Boolean} whether to bind the buffer before uploading it - */ -Buffer.prototype.upload = function(data, offset, dontBind) -{ - // todo - needed? - if(!dontBind) this.bind(); - - var gl = this.gl; - - data = data || this.data; - offset = offset || 0; - - if(this.data.byteLength >= data.byteLength) - { - gl.bufferSubData(this.type, offset, data); - } - else - { - gl.bufferData(this.type, data, this.drawType); - } - - this.data = data; -}; -/** - * Binds the buffer - * - */ -Buffer.prototype.bind = function() -{ - var gl = this.gl; - gl.bindBuffer(this.type, this.buffer); -}; - -Buffer.createVertexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ARRAY_BUFFER, data, drawType); -}; - -Buffer.createIndexBuffer = function(gl, data, drawType) -{ - return new Buffer(gl, gl.ELEMENT_ARRAY_BUFFER, data, drawType); -}; - -Buffer.create = function(gl, type, data, drawType) -{ - return new Buffer(gl, type, data, drawType); -}; - -/** - * Destroys the buffer - * - */ -Buffer.prototype.destroy = function(){ - this.gl.deleteBuffer(this.buffer); -}; - -module.exports = Buffer; diff --git a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js index 3f95a06..67d9742 100644 --- a/src/core/renderers/webgl/systems/geometry/GeometrySystem.js +++ b/src/core/renderers/webgl/systems/geometry/GeometrySystem.js @@ -1,18 +1,22 @@ import WebGLSystem from '../WebGLSystem'; -import { Rectangle, Matrix } from '../../../../math'; -import VertexArrayObject from './VertexArrayObject'; -import GLBuffer from './GLBuffer'; -import setVertexAttribArrays from './setVertexAttribArrays'; - const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; +class GLBufferData +{ + constructor(buffer) + { + this.buffer = buffer; + this.updateID = -1; + this.byteLength = -1; + } +} + /** * @class * @extends PIXI.WebGLSystem * @memberof PIXI */ - export default class GeometrySystem extends WebGLSystem { /** @@ -37,43 +41,63 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // webgl2 - if(!gl.createVertexArray) + if (!gl.createVertexArray) { // webgl 1! - const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); + const nativeVaoExtension = gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'); - if(nativeVaoExtension) + if (nativeVaoExtension) { - gl.createVertexArray = nativeVaoExtension.createVertexArrayOES; - gl.bindVertexArray = nativeVaoExtension.bindVertexArrayOES; - gl.deleteVertexArray = nativeVaoExtension.deleteVertexArrayOES; + gl.createVertexArray = () => + nativeVaoExtension.createVertexArrayOES(); + + gl.bindVertexArray = (vao) => + { + nativeVaoExtension.bindVertexArrayOES(vao); + }; + + gl.deleteVertexArray = (vao) => + { + nativeVaoExtension.deleteVertexArrayOES(vao); + }; } else { this.hasVao = false; - gl.createVertexArray = ()=>{return {}} - gl.bindVertexArray = ()=>{} - gl.deleteVertexArray = ()=>{} + gl.createVertexArray = () => + { + // empty + }; + + gl.bindVertexArray = () => + { + // empty + }; + + gl.deleteVertexArray = () => + { + // empty + }; } } - if(!gl.vertexAttribDivisor) + if (!gl.vertexAttribDivisor) { - const instanceExt = gl.getExtension("ANGLE_instanced_arrays"); + const instanceExt = gl.getExtension('ANGLE_instanced_arrays'); - if(instanceExt) + if (instanceExt) { gl.vertexAttribDivisor = instanceExt.vertexAttribDivisorANGLE; gl.drawElementsInstanced = instanceExt.drawElementsInstancedANGLE; - gl.drawArrayInstanced = instanceExt.drawArraysInstancedANGLE; + gl.drawArraysInstanced = instanceExt.drawArraysInstancedANGLE; } } - } /** @@ -87,27 +111,26 @@ const gl = this.gl; - // not sure the best way to address this.. // currently different shaders require different VAOs for the same geometry // Still mulling over the best way to solve this one.. // will likely need to modify the shader attribute locations at run time! let vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if(!vaos) + if (!vaos) { - vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID] = {}; + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; } const vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); this._activeGeometry = geometry; - if(this._activeVao !== vao) + if (this._activeVao !== vao) { this._activeVao = vao; - if(this.hasVao) + if (this.hasVao) { gl.bindVertexArray(vao); } @@ -123,7 +146,6 @@ this.updateBuffers(); } - updateBuffers() { const geometry = this._activeGeometry; @@ -135,9 +157,9 @@ const glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer._updateID) + if (buffer._updateID !== glBuffer.updateID) { - glBuffer._updateID = buffer._updateID; + glBuffer.updateID = buffer._updateID; // TODO can cache this on buffer! maybe added a getter / setter? const type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; @@ -145,7 +167,7 @@ gl.bindBuffer(type, glBuffer.buffer); - if(glBuffer.byteLength >= buffer.data.byteLength) + if (glBuffer.byteLength >= buffer.data.byteLength) { // offset is always zero for now! gl.bufferSubData(type, 0, buffer.data); @@ -154,7 +176,6 @@ { gl.bufferData(type, buffer.data, drawType); } - } } } @@ -167,9 +188,9 @@ for (const j in shaderAttributes) { - if(!geometryAttributes[j]) + if (!geometryAttributes[j]) { - throw new Error('shader and geometry incompatible, geometry missing the "' + j + '" attribute'); + throw new Error(`shader and geometry incompatible, geometry missing the "${j}" attribute`); } } } @@ -178,7 +199,6 @@ * Creates a Vao with the same structure as the geometry and stores it on the geometry. * @private * @param {PIXI.mesh.Geometry} geometry instance of geometry to to generate Vao for - * @return {PIXI.VertexArrayObject} Returns a fresh vao. */ initGeometryVao(geometry, program) { @@ -189,17 +209,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - // first update - and create the buffers! - for (let i = 0; i < buffers.length; i++) - { - const buffer = buffers[i]; - - if (!buffer._glBuffers[CONTEXT_UID]) - { - buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); - } - } - const tempStride = {}; const tempStart = {}; @@ -211,7 +220,7 @@ for (const j in attributes) { - if(!attributes[j].size && program.attributeData[j]) + if (!attributes[j].size && program.attributeData[j]) { attributes[j].size = program.attributeData[j].size; } @@ -224,8 +233,6 @@ const attribute = attributes[j]; const attribSize = attribute.size; - // must be careful that the geometry has attributes not used by this shader.. - if (attribute.stride === undefined) { if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) @@ -246,6 +253,18 @@ } } + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (let i = 0; i < buffers.length; i++) + { + const buffer = buffers[i]; + + if (!buffer._glBuffers[CONTEXT_UID]) + { + buffer._glBuffers[CONTEXT_UID] = new GLBufferData(gl.createBuffer()); + } + } + // TODO - maybe make this a data object? // lets wait to see if we need to first! const vao = gl.createVertexArray(); @@ -256,8 +275,8 @@ gl.bindVertexArray(null); - geometry.glVertexArrayObjects[CONTEXT_UID][program.id] = vao; - + // add it to the cache! + geometry.glVertexArrayObjects[this.CONTEXT_UID][program.id] = vao; } activateVao(geometry, program) @@ -267,7 +286,6 @@ const buffers = geometry.buffers; const attributes = geometry.attributes; - if (geometry.indexBuffer) { // first update the index buffer if we have one.. @@ -283,9 +301,9 @@ const buffer = buffers[attribute.buffer]; const glBuffer = buffer._glBuffers[CONTEXT_UID]; - if(program.attributeData[j]) + if (program.attributeData[j]) { - if(lastBuffer !== glBuffer) + if (lastBuffer !== glBuffer) { gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); @@ -294,8 +312,8 @@ const location = program.attributeData[j].location; - //TODO introduce state again - //we can optimise this for older devices that have no VAOs + // TODO introduce state again + // we can optimise this for older devices that have no VAOs gl.enableVertexAttribArray(location); gl.vertexAttribPointer(location, @@ -305,10 +323,10 @@ attribute.stride, attribute.start); - if(attribute.instance) + if (attribute.instance) { - //TODO calculate instance count based of this... - if(this.hasInstance) + // TODO calculate instance count based of this... + if (this.hasInstance) { gl.vertexAttribDivisor(location, 1); } @@ -326,62 +344,32 @@ const gl = this.gl; const geometry = this._activeGeometry; - //TODO.. this should not change so maybe cache the function? + // TODO.. this should not change so maybe cache the function? - if(geometry.indexBuffer) + if (geometry.indexBuffer) { - if(geometry.instanced) + if (geometry.instanced) { + /* eslint-disable max-len */ gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); + /* eslint-enable max-len */ } else { - gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); + gl.drawElements(type, size || geometry.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2); } } else - { - if(geometry.instanced) + if (geometry.instanced) { // TODO need a better way to calculate size.. - gl.drawArrayInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } else { - gl.drawArrays(type, start, size || geometry.getSize()); - } + gl.drawArrays(type, start, size || geometry.getSize()); } return this; } - - /** - * Creates a new VAO from this renderer's context and state. - * - * @return {VertexArrayObject} The new VAO. - */ - createVao() - { - return new VertexArrayObject(this.gl, this.renderer.state.attribState); - } - - /** - * Changes the current Vao to the one given in parameter - * - * @param {PIXI.VertexArrayObject} vao - the new Vao - * @return {PIXI.WebGLRenderer} Returns itself. - */ - bindVao(vao) - { - } -} - -class GLBufferData -{ - constructor(buffer) - { - this.buffer = buffer; - this.updateID = -1; - this.byteLength = -1; - } } diff --git a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js b/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js deleted file mode 100644 index 78cfa5f..0000000 --- a/src/core/renderers/webgl/systems/geometry/VertexArrayObject.js +++ /dev/null @@ -1,295 +0,0 @@ - -// state object// -var setVertexAttribArrays = require( './setVertexAttribArrays' ); - - -/** - * Helper class to work with WebGL VertexArrayObjects (vaos) - * Only works if WebGL extensions are enabled (they usually are) - * - * @class - * @memberof PIXI.glCore - * @param gl {WebGLRenderingContext} The current WebGL rendering context - */ -function VertexArrayObject(gl, state) -{ - this.nativeVaoExtension = null; - - if(!VertexArrayObject.FORCE_NATIVE) - { - this.nativeVaoExtension = gl.getExtension('OES_vertex_array_object') || - gl.getExtension('MOZ_OES_vertex_array_object') || - gl.getExtension('WEBKIT_OES_vertex_array_object'); - - this.instanceExt = gl.getExtension("ANGLE_instanced_arrays"); - } - - - this.nativeState = state; - - if(this.nativeVaoExtension) - { - this.nativeVao = this.nativeVaoExtension.createVertexArrayOES(); - - var maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS); - - // VAO - overwrite the state.. - this.nativeState = { - tempAttribState: new Array(maxAttribs), - attribState: new Array(maxAttribs) - }; - } - - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; - - /** - * An array of attributes - * - * @member {Array} - */ - this.attributes = []; - - /** - * @member {PIXI.glCore.GLBuffer} - */ - this.indexBuffer = null; - - /** - * A boolean flag - * - * @member {Boolean} - */ - this.dirty = false; -} - -VertexArrayObject.prototype.constructor = VertexArrayObject; -module.exports = VertexArrayObject; - -/** -* Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) -* If you find on older devices that things have gone a bit weird then set this to true. -*/ -/** - * Lets the VAO know if you should use the WebGL extension or the native methods. - * Some devices behave a bit funny when using the newer extensions (im looking at you ipad 2!) - * If you find on older devices that things have gone a bit weird then set this to true. - * @static - * @property {Boolean} FORCE_NATIVE - */ -VertexArrayObject.FORCE_NATIVE = false; - -/** - * Binds the buffer - */ -VertexArrayObject.prototype.bind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - - if(this.dirty) - { - this.dirty = false; - this.activate(); - } - } - else - { - - this.activate(); - } - - return this; -}; - -/** - * Unbinds the buffer - */ -VertexArrayObject.prototype.unbind = function() -{ - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(null); - } - - return this; -}; - -/** - * Uses this vao - */ -VertexArrayObject.prototype.activate = function() -{ - - var gl = this.gl; - var lastBuffer = null; - - for (var i = 0; i < this.attributes.length; i++) - { - var attrib = this.attributes[i]; - - if(lastBuffer !== attrib.buffer) - { - attrib.buffer.bind(); - lastBuffer = attrib.buffer; - } - - gl.vertexAttribPointer(attrib.attribute.location, - attrib.attribute.size, - attrib.type || gl.FLOAT, - attrib.normalized || false, - attrib.stride || 0, - attrib.start || 0); - - if(attrib.instance) - { - if(this.instanceExt) - { - this.instanceExt.vertexAttribDivisorANGLE(attrib.attribute.location, 1); - } - else - { - console.warn('instancing not supported by this device :/') - } - } - } - - setVertexAttribArrays(gl, this.attributes, this.nativeState); - - if(this.indexBuffer) - { - this.indexBuffer.bind(); - } - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - * @param attribute {*} - * @param type {String} - * @param normalized {Boolean} - * @param stride {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.addAttribute = function(buffer, attribute, type, normalized, stride, start, instance) -{ - this.attributes.push({ - buffer: buffer, - attribute: attribute, - - location: attribute.location, - type: type || this.gl.FLOAT, - normalized: normalized || false, - stride: stride || 0, - start: start || 0, - instance: instance - }); - - this.instancedMesh = this.instancedMesh || instance; - - this.dirty = true; - - return this; -}; - -/** - * - * @param buffer {PIXI.gl.GLBuffer} - */ -VertexArrayObject.prototype.addIndex = function(buffer/*, options*/) -{ - this.indexBuffer = buffer; - - this.dirty = true; - - return this; -}; - -/** - * Unbinds this vao and disables it - */ -VertexArrayObject.prototype.clear = function() -{ - // var gl = this.gl; - - // TODO - should this function unbind after clear? - // for now, no but lets see what happens in the real world! - if(this.nativeVao) - { - this.nativeVaoExtension.bindVertexArrayOES(this.nativeVao); - } - - this.attributes.length = 0; - this.indexBuffer = null; - - return this; -}; - -/** - * @param type {Number} - * @param size {Number} - * @param start {Number} - */ -VertexArrayObject.prototype.draw = function(type, size, start, instanceCount) -{ - var gl = this.gl; - - if(this.indexBuffer) - { - if(this.instancedMesh) - { - this.instanceExt.drawElementsInstancedANGLE(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2, instanceCount || 1); - } - else - { - gl.drawElements(type, size || this.indexBuffer.data.length, gl.UNSIGNED_SHORT, (start || 0) * 2 ); - } - } - else - { - if(this.instancedMesh) - { - // TODO need a better way to calculate size.. - this.instanceExt.drawArrayInstancedANGLE(type, start, size || this.getSize(), instanceCount || 1); - } - else - { - gl.drawArrays(type, start, size || this.getSize()); - } - } - - return this; -}; - -/** - * Destroy this vao - */ -VertexArrayObject.prototype.destroy = function() -{ - // lose references - this.gl = null; - this.indexBuffer = null; - this.attributes = null; - this.nativeState = null; - - if(this.nativeVao) - { - this.nativeVaoExtension.deleteVertexArrayOES(this.nativeVao); - } - - this.nativeVaoExtension = null; - this.nativeVao = null; -}; - -VertexArrayObject.prototype.getSize = function() -{ - var attrib = this.attributes[0]; - return attrib.buffer.data.length / (( attrib.stride/4 ) || attrib.attribute.size); -}; diff --git a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js index 4bc437a..23b6959 100644 --- a/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js +++ b/src/core/renderers/webgl/systems/geometry/setVertexAttribArrays.js @@ -5,13 +5,14 @@ * @param attribs {*} * @param state {*} */ -var setVertexAttribArrays = function (gl, attribs, state) +export default function setVertexAttribArrays(gl, attribs, state) { - var i; - if(state) + let i; + + if (state) { - var tempAttribState = state.tempAttribState, - attribState = state.attribState; + const tempAttribState = state.tempAttribState; + const attribState = state.attribState; for (i = 0; i < tempAttribState.length; i++) { @@ -40,16 +41,14 @@ } } } - } else { for (i = 0; i < attribs.length; i++) { - var attrib = attribs[i]; + const attrib = attribs[i]; + gl.enableVertexAttribArray(attrib.attribute.location); } } -}; - -module.exports = setVertexAttribArrays; +} diff --git a/src/core/renderers/webgl/systems/shader/GLShader.js b/src/core/renderers/webgl/systems/shader/GLShader.js index 6ab6d8d..d0b6505 100644 --- a/src/core/renderers/webgl/systems/shader/GLShader.js +++ b/src/core/renderers/webgl/systems/shader/GLShader.js @@ -1,11 +1,10 @@ +import compileProgram from './shader/compileProgram'; +import extractAttributes from './shader/extractAttributes'; +import extractUniforms from './shader/extractUniforms'; +import setPrecision from './shader/setPrecision'; +import generateUniformAccessObject from './shader/generateUniformAccessObject'; -var compileProgram = require('./shader/compileProgram'), - extractAttributes = require('./shader/extractAttributes'), - extractUniforms = require('./shader/extractUniforms'), - setPrecision = require('./shader/setPrecision'), - generateUniformAccessObject = require('./shader/generateUniformAccessObject'); - -var ID = 0; +let ID = 0; /** * Helper class to create a webGL Shader @@ -16,81 +15,84 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. * @param precision {string} The float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param attributeLocations {object} A key value pair showing which location eact attribute should sit eg {position:0, uvs:1} + * @param attributeLocations {object} A key value pair showing which location eact + * attribute should sit eg {position:0, uvs:1} */ -var Shader = function(gl, vertexSrc, fragmentSrc, precision, attributeLocations) +export default class Shader { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, vertexSrc, fragmentSrc, precision, attributeLocations) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; - if(precision) - { - vertexSrc = setPrecision(vertexSrc, precision); - fragmentSrc = setPrecision(fragmentSrc, precision); - } + if (precision) + { + vertexSrc = setPrecision(vertexSrc, precision); + fragmentSrc = setPrecision(fragmentSrc, precision); + } - /** - * The shader program - * - * @member {WebGLProgram} - */ - // First compile the program.. - this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); + /** + * The shader program + * + * @member {WebGLProgram} + */ + // First compile the program.. + this.program = compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations); - /** - * The attributes of the shader as an object containing the following properties - * { - * type, - * size, - * location, - * pointer - * } - * @member {Object} - */ - // next extract the attributes - this.attributes = extractAttributes(gl, this.program); + /** + * The attributes of the shader as an object containing the following properties + * { + * type, + * size, + * location, + * pointer + * } + * @member {Object} + */ + // next extract the attributes + this.attributes = extractAttributes(gl, this.program); - this.uniformData = extractUniforms(gl, this.program); + this.uniformData = extractUniforms(gl, this.program); - /** - * The uniforms of the shader as an object containing the following properties - * { - * gl, - * data - * } - * @member {Object} - */ - this.uniforms = generateUniformAccessObject( gl, this.uniformData ); + /** + * The uniforms of the shader as an object containing the following properties + * { + * gl, + * data + * } + * @member {Object} + */ + this.uniforms = generateUniformAccessObject(gl, this.uniformData); - this.uniformGroups = {}; + this.uniformGroups = {}; - this.id = ID++; -}; -/** - * Uses this shader - */ -Shader.prototype.bind = function() -{ - this.gl.useProgram(this.program); -}; + this.id = ID++; + } -/** - * Destroys this shader - * TODO - */ -Shader.prototype.destroy = function() -{ - this.attributes = null; - this.uniformData = null; - this.uniforms = null; + /** + * Uses this shader + */ + bind() + { + this.gl.useProgram(this.program); + } - var gl = this.gl; - gl.deleteProgram(this.program); -}; + /** + * Destroys this shader + * TODO + */ + destroy() + { + this.attributes = null; + this.uniformData = null; + this.uniforms = null; + const gl = this.gl; -module.exports = Shader; + gl.deleteProgram(this.program); + } +} diff --git a/src/core/renderers/webgl/systems/shader/ShaderSystem.js b/src/core/renderers/webgl/systems/shader/ShaderSystem.js index 670dd72..aaa13df 100644 --- a/src/core/renderers/webgl/systems/shader/ShaderSystem.js +++ b/src/core/renderers/webgl/systems/shader/ShaderSystem.js @@ -18,7 +18,6 @@ */ constructor(renderer) { - super(renderer); /** @@ -29,6 +28,7 @@ this.gl = null; this.shader = null; + this.program = null; this.id = UID++; } @@ -53,10 +53,12 @@ const program = shader.program; const glShader = program.glShaders[this.renderer.CONTEXT_UID] || this.generateShader(shader); + this.shader = shader; + // TODO - some current pixi plugins bypass this.. so it not safe to use yet.. - if (this.shader !== shader) + if (this.program !== program) { - this.shader = shader; + this.program = program; glShader.bind(); } @@ -85,14 +87,13 @@ { const glShader = this.getGLShader(); - if(!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) + if (!group.static || group.dirtyId !== glShader.uniformGroups[group.id]) { glShader.uniformGroups[group.id] = group.dirtyId; const syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); syncFunc(glShader.uniformData, group.uniforms, this.renderer); } - } createSyncGroups(group) @@ -110,14 +111,12 @@ */ getGLShader() { - if(this.shader) + if (this.shader) { return this.shader.program.glShaders[this.renderer.CONTEXT_UID]; } - else - { - return null; - } + + return null; } /** diff --git a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js index cefca34..5ef4ca3 100644 --- a/src/core/renderers/webgl/systems/shader/shader/compileProgram.js +++ b/src/core/renderers/webgl/systems/shader/shader/compileProgram.js @@ -1,4 +1,3 @@ - /** * @class * @memberof PIXI.glCore.shader @@ -8,26 +7,25 @@ * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations * @return {WebGLProgram} the shader program */ -var compileProgram = function(gl, vertexSrc, fragmentSrc, attributeLocations) +export default function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); + const glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); + const glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); + let program = gl.createProgram(); gl.attachShader(program, glVertShader); gl.attachShader(program, glFragShader); // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if(attributeLocations) + if (attributeLocations) { - for(var i in attributeLocations) + for (const i in attributeLocations) { gl.bindAttribLocation(program, attributeLocations[i], i); } } - gl.linkProgram(program); // if linking fails, then log and cleanup @@ -52,7 +50,7 @@ gl.deleteShader(glFragShader); return program; -}; +} /** * @private @@ -61,20 +59,17 @@ * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. * @return {WebGLShader} the shader */ -var compileShader = function (gl, type, src) +function compileShader(gl, type, src) { - var shader = gl.createShader(type); + const shader = gl.createShader(type); gl.shaderSource(shader, src); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - console.log(gl.getShaderInfoLog(shader)); return null; } return shader; -}; - -module.exports = compileProgram; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js index 9f82434..556fac6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/defaultValue.js +++ b/src/core/renderers/webgl/systems/shader/shader/defaultValue.js @@ -4,7 +4,7 @@ * @param type {String} Type of value * @param size {Number} */ -var defaultValue = function(type, size) +export default function defaultValue(type, size) { switch (type) { @@ -39,7 +39,7 @@ case 'bvec2': - return booleanArray( 2 * size); + return booleanArray(2 * size); case 'bvec3': return booleanArray(3 * size); @@ -49,31 +49,31 @@ case 'mat2': return new Float32Array([1, 0, - 0, 1]); + 0, 1]); case 'mat3': return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); + 0, 1, 0, + 0, 0, 1]); case 'mat4': return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); } -}; -var booleanArray = function(size) + return null; +} + +function booleanArray(size) { - var array = new Array(size); + const array = new Array(size); - for (var i = 0; i < array.length; i++) + for (let i = 0; i < array.length; i++) { array[i] = false; } return array; -}; - -module.exports = defaultValue; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js index 313f078..e8b006a 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractAttributes.js @@ -1,6 +1,5 @@ - -var mapType = require('./mapType'); -var mapSize = require('./mapSize'); +import mapType from './mapType'; +import mapSize from './mapSize'; /** * Extracts the attributes @@ -10,32 +9,30 @@ * @param program {WebGLProgram} The shader program to get the attributes from * @return attributes {Object} */ -var extractAttributes = function(gl, program) +export default function extractAttributes(gl, program) { - var attributes = {}; + const attributes = {}; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + const totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) + for (let i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); + const attribData = gl.getActiveAttrib(program, i); + const type = mapType(gl, attribData.type); attributes[attribData.name] = { - type:type, - size:mapSize(type), - location:gl.getAttribLocation(program, attribData.name), - //TODO - make an attribute object - pointer: pointer + type, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + // TODO - make an attribute object + pointer, }; } return attributes; -}; +} -var pointer = function(type, normalized, stride, start){ - // console.log(this.location) - gl.vertexAttribPointer(this.location,this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); -}; - -module.exports = extractAttributes; +function pointer()// type, normalized, stride, start) +{ + // gl.vertexAttribPointer(this.location, this.size, type || gl.FLOAT, normalized || false, stride || 0, start || 0); +} diff --git a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js index 78d9f0d..3191265 100644 --- a/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js +++ b/src/core/renderers/webgl/systems/shader/shader/extractUniforms.js @@ -1,5 +1,5 @@ -var mapType = require('./mapType'); -var defaultValue = require('./defaultValue'); +import mapType from './mapType'; +import defaultValue from './defaultValue'; /** * Extracts the uniforms @@ -9,27 +9,25 @@ * @param program {WebGLProgram} The shader program to get the uniforms from * @return uniforms {Object} */ -var extractUniforms = function(gl, program) +export default function extractUniforms(gl, program) { - var uniforms = {}; + const uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + const totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - for (var i = 0; i < totalUniforms; i++) + for (let i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]/, ""); - var type = mapType(gl, uniformData.type ); + const uniformData = gl.getActiveUniform(program, i); + const name = uniformData.name.replace(/\[.*?\]/, ''); + const type = mapType(gl, uniformData.type); - uniforms[name] = { - type:type, - size:uniformData.size, - location:gl.getUniformLocation(program, name), - value:defaultValue(type, uniformData.size) - }; + uniforms[name] = { + type, + size: uniformData.size, + location: gl.getUniformLocation(program, name), + value: defaultValue(type, uniformData.size), + }; } - return uniforms; -}; - -module.exports = extractUniforms; + return uniforms; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js index c2aa597..9b09ee2 100644 --- a/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js +++ b/src/core/renderers/webgl/systems/shader/shader/generateUniformAccessObject.js @@ -1,3 +1,61 @@ +const getterTemplate = [ + 'return this.data.%%.value;', +].join('\n'); + +const setterTemplate = [ + 'this.data.%%.value = value;', + 'var location = this.data.%%.location;', +].join('\n'); + +const GLSL_TO_SINGLE_SETTERS = { + + float: 'uniform1f(location, value)', + + vec2: 'uniform2f(location, value[0], value[1])', + vec3: 'uniform3f(location, value[0], value[1], value[2])', + vec4: 'uniform4f(location, value[0], value[1], value[2], value[3])', + + int: 'uniform1i(location, value)', + ivec2: 'uniform2i(location, value[0], value[1])', + ivec3: 'uniform3i(location, value[0], value[1], value[2])', + ivec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + bool: 'uniform1i(location, value)', + bvec2: 'uniform2i(location, value[0], value[1])', + bvec3: 'uniform3i(location, value[0], value[1], value[2])', + bvec4: 'uniform4i(location, value[0], value[1], value[2], value[3])', + + mat2: 'uniformMatrix2fv(location, false, value)', + mat3: 'uniformMatrix3fv(location, false, value)', + mat4: 'uniformMatrix4fv(location, false, value)', + + sampler2D: 'uniform1i(location, value)', + samplerCube: 'uniform1i(location, value)', + +}; + +const GLSL_TO_ARRAY_SETTERS = { + + float: 'uniform1fv(location, value)', + + vec2: 'uniform2fv(location, value)', + vec3: 'uniform3fv(location, value)', + vec4: 'uniform4fv(location, value)', + + int: 'uniform1iv(location, value)', + ivec2: 'uniform2iv(location, value)', + ivec3: 'uniform3iv(location, value)', + ivec4: 'uniform4iv(location, value)', + + bool: 'uniform1iv(location, value)', + bvec2: 'uniform2iv(location, value)', + bvec3: 'uniform3iv(location, value)', + bvec4: 'uniform4iv(location, value)', + + sampler2D: 'uniform1iv(location, value)', + samplerCube: 'uniform1i(location, value)', +}; + /** * Extracts the attributes * @class @@ -6,52 +64,53 @@ * @param uniforms {Array} @mat ? * @return attributes {Object} */ -var generateUniformAccessObject = function(gl, uniformData) +export default function generateUniformAccessObject(gl, uniformData) { // this is the object we will be sending back. // an object hierachy will be created for structs - var uniforms = {data:{}}; + const uniforms = { data: {} }; uniforms.gl = gl; - var uniformKeys= Object.keys(uniformData); + const uniformKeys = Object.keys(uniformData); - for (var i = 0; i < uniformKeys.length; i++) + for (let i = 0; i < uniformKeys.length; i++) { - var fullName = uniformKeys[i]; + const fullName = uniformKeys[i]; - var nameTokens = fullName.split('.'); - var name = nameTokens[nameTokens.length - 1]; + const nameTokens = fullName.split('.'); + const name = nameTokens[nameTokens.length - 1]; + const uniformGroup = getUniformGroup(nameTokens, uniforms); - var uniformGroup = getUniformGroup(nameTokens, uniforms); + const uniform = uniformData[fullName]; - var uniform = uniformData[fullName]; uniformGroup.data[name] = uniform; uniformGroup.gl = gl; Object.defineProperty(uniformGroup, name, { get: generateGetter(name), - set: generateSetter(name, uniform) + set: generateSetter(name, uniform), }); } return uniforms; -}; +} -var generateGetter = function(name) +function generateGetter(name) { - var template = getterTemplate.replace('%%', name); - return new Function(template); // jshint ignore:line -}; + const template = getterTemplate.replace('%%', name); -var generateSetter = function(name, uniform) + return new Function(template); // eslint-disable-line no-new-func +} + +function generateSetter(name, uniform) { - var template = setterTemplate.replace(/%%/g, name); - var setTemplate; + let template = setterTemplate.replace(/%%/g, name); + let setTemplate; - if(uniform.size === 1) + if (uniform.size === 1) { setTemplate = GLSL_TO_SINGLE_SETTERS[uniform.type]; } @@ -60,85 +119,25 @@ setTemplate = GLSL_TO_ARRAY_SETTERS[uniform.type]; } - if(setTemplate) + if (setTemplate) { - template += "\nthis.gl." + setTemplate + ";"; + template += `\nthis.gl.${setTemplate};`; } - return new Function('value', template); // jshint ignore:line -}; + return new Function('value', template); // eslint-disable-line no-new-func +} -var getUniformGroup = function(nameTokens, uniform) +function getUniformGroup(nameTokens, uniform) { - var cur = uniform; + let cur = uniform; - for (var i = 0; i < nameTokens.length - 1; i++) + for (let i = 0; i < nameTokens.length - 1; i++) { - var o = cur[nameTokens[i]] || {data:{}}; + const o = cur[nameTokens[i]] || { data: {} }; + cur[nameTokens[i]] = o; cur = o; } return cur; -}; - -var getterTemplate = [ - 'return this.data.%%.value;', -].join('\n'); - -var setterTemplate = [ - 'this.data.%%.value = value;', - 'var location = this.data.%%.location;' -].join('\n'); - - -var GLSL_TO_SINGLE_SETTERS = { - - 'float': 'uniform1f(location, value)', - - 'vec2': 'uniform2f(location, value[0], value[1])', - 'vec3': 'uniform3f(location, value[0], value[1], value[2])', - 'vec4': 'uniform4f(location, value[0], value[1], value[2], value[3])', - - 'int': 'uniform1i(location, value)', - 'ivec2': 'uniform2i(location, value[0], value[1])', - 'ivec3': 'uniform3i(location, value[0], value[1], value[2])', - 'ivec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'bool': 'uniform1i(location, value)', - 'bvec2': 'uniform2i(location, value[0], value[1])', - 'bvec3': 'uniform3i(location, value[0], value[1], value[2])', - 'bvec4': 'uniform4i(location, value[0], value[1], value[2], value[3])', - - 'mat2': 'uniformMatrix2fv(location, false, value)', - 'mat3': 'uniformMatrix3fv(location, false, value)', - 'mat4': 'uniformMatrix4fv(location, false, value)', - - 'sampler2D':'uniform1i(location, value)', - 'samplerCube': 'uniform1i(location, value)' - -}; - -var GLSL_TO_ARRAY_SETTERS = { - - 'float': 'uniform1fv(location, value)', - - 'vec2': 'uniform2fv(location, value)', - 'vec3': 'uniform3fv(location, value)', - 'vec4': 'uniform4fv(location, value)', - - 'int': 'uniform1iv(location, value)', - 'ivec2': 'uniform2iv(location, value)', - 'ivec3': 'uniform3iv(location, value)', - 'ivec4': 'uniform4iv(location, value)', - - 'bool': 'uniform1iv(location, value)', - 'bvec2': 'uniform2iv(location, value)', - 'bvec3': 'uniform3iv(location, value)', - 'bvec4': 'uniform4iv(location, value)', - - 'sampler2D':'uniform1iv(location, value)', - 'samplerCube': 'uniform1i(location, value)' -}; - -module.exports = generateUniformAccessObject; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/index.js b/src/core/renderers/webgl/systems/shader/shader/index.js index e08684d..5156a37 100644 --- a/src/core/renderers/webgl/systems/shader/shader/index.js +++ b/src/core/renderers/webgl/systems/shader/shader/index.js @@ -1,10 +1,8 @@ -module.exports = { - compileProgram: require('./compileProgram'), - defaultValue: require('./defaultValue'), - extractAttributes: require('./extractAttributes'), - extractUniforms: require('./extractUniforms'), - generateUniformAccessObject: require('./generateUniformAccessObject'), - setPrecision: require('./setPrecision'), - mapSize: require('./mapSize'), - mapType: require('./mapType') -}; \ No newline at end of file +export { default as compileProgram } from './compileProgram'; +export { default as defaultValue } from './defaultValue'; +export { default as extractAttributes } from './extractAttributes'; +export { default as extractUniforms } from './extractUniforms'; +export { default as generateUniformAccessObject } from './generateUniformAccessObject'; +export { default as setPrecision } from './setPrecision'; +export { default as mapSize } from './mapSize'; +export { default as mapType } from './mapType'; diff --git a/src/core/renderers/webgl/systems/shader/shader/mapSize.js b/src/core/renderers/webgl/systems/shader/shader/mapSize.js index 61d9b36..10052e6 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapSize.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapSize.js @@ -1,36 +1,33 @@ +const GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + + mat2: 4, + mat3: 9, + mat4: 16, + + sampler2D: 1, +}; + /** * @class * @memberof PIXI.glCore.shader * @param type {String} * @return {Number} */ -var mapSize = function(type) -{ +export default function mapSize(type) +{ return GLSL_TO_SIZE[type]; -}; - - -var GLSL_TO_SIZE = { - 'float': 1, - 'vec2': 2, - 'vec3': 3, - 'vec4': 4, - - 'int': 1, - 'ivec2': 2, - 'ivec3': 3, - 'ivec4': 4, - - 'bool': 1, - 'bvec2': 2, - 'bvec3': 3, - 'bvec4': 4, - - 'mat2': 4, - 'mat3': 9, - 'mat4': 16, - - 'sampler2D': 1 -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/mapType.js b/src/core/renderers/webgl/systems/shader/shader/mapType.js index aa837e2..d288b7c 100644 --- a/src/core/renderers/webgl/systems/shader/shader/mapType.js +++ b/src/core/renderers/webgl/systems/shader/shader/mapType.js @@ -1,49 +1,45 @@ +let GL_TABLE = null; +const GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', -var mapSize = function(gl, type) + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + + SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', +}; + +export default function mapType(gl, type) { - if(!GL_TABLE) + if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); + const typeNames = Object.keys(GL_TO_GLSL_TYPES); GL_TABLE = {}; - for(var i = 0; i < typeNames.length; ++i) + for (let i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[ gl[tn] ] = GL_TO_GLSL_TYPES[tn]; + const tn = typeNames[i]; + + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; } } - // console.log(gl) return GL_TABLE[type]; -}; - -var GL_TABLE = null; - -var GL_TO_GLSL_TYPES = { - 'FLOAT': 'float', - 'FLOAT_VEC2': 'vec2', - 'FLOAT_VEC3': 'vec3', - 'FLOAT_VEC4': 'vec4', - - 'INT': 'int', - 'INT_VEC2': 'ivec2', - 'INT_VEC3': 'ivec3', - 'INT_VEC4': 'ivec4', - - 'BOOL': 'bool', - 'BOOL_VEC2': 'bvec2', - 'BOOL_VEC3': 'bvec3', - 'BOOL_VEC4': 'bvec4', - - 'FLOAT_MAT2': 'mat2', - 'FLOAT_MAT3': 'mat3', - 'FLOAT_MAT4': 'mat4', - - 'SAMPLER_2D': 'sampler2D', - 'SAMPLER_CUBE': 'samplerCube', - 'SAMPLER_2D_ARRAY': 'sampler2DArray' -}; - -module.exports = mapSize; +} diff --git a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js index a765378..e5ae38e 100644 --- a/src/core/renderers/webgl/systems/shader/shader/setPrecision.js +++ b/src/core/renderers/webgl/systems/shader/shader/setPrecision.js @@ -5,14 +5,12 @@ * * @return {string} modified shader source */ -var setPrecision = function(src, precision) +export default function setPrecision(src, precision) { - if(src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') + if (src.substring(0, 9) !== 'precision' && src.substring(0, 1) !== '#') { - return 'precision ' + precision + ' float;\n' + src; + return `precision ${precision} float;\n${src}`; } return src; -}; - -module.exports = setPrecision; +} diff --git a/src/core/renderers/webgl/systems/textures/GLTexture.js b/src/core/renderers/webgl/systems/textures/GLTexture.js index cb8f6ad..78d00ec 100644 --- a/src/core/renderers/webgl/systems/textures/GLTexture.js +++ b/src/core/renderers/webgl/systems/textures/GLTexture.js @@ -1,3 +1,4 @@ +let FLOATING_POINT_AVAILABLE = false; /** * Helper class to create a WebGL Texture @@ -10,324 +11,314 @@ * @param format {number} the pixel format of the texture. defaults to gl.RGBA * @param type {number} the gl type of the texture. defaults to gl.UNSIGNED_BYTE */ -var Texture = function(gl, width, height, format, type) +export default class Texture { - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - this.gl = gl; + constructor(gl, width, height, format, type) + { + /** + * The current WebGL rendering context + * + * @member {WebGLRenderingContext} + */ + this.gl = gl; + /** + * The WebGL texture + * + * @member {WebGLTexture} + */ + this.texture = gl.createTexture(); - /** - * The WebGL texture - * - * @member {WebGLTexture} - */ - this.texture = gl.createTexture(); + /** + * If mipmapping was used for this texture, enable and disable with enableMipmap() + * + * @member {Boolean} + */ + // some settings.. + this.mipmap = false; - /** - * If mipmapping was used for this texture, enable and disable with enableMipmap() - * - * @member {Boolean} - */ - // some settings.. - this.mipmap = false; + /** + * Set to true to enable pre-multiplied alpha + * + * @member {Boolean} + */ + this.premultiplyAlpha = false; + /** + * The width of texture + * + * @member {Number} + */ + this.width = width || -1; + /** + * The height of texture + * + * @member {Number} + */ + this.height = height || -1; - /** - * Set to true to enable pre-multiplied alpha - * - * @member {Boolean} - */ - this.premultiplyAlpha = false; + /** + * The pixel format of the texture. defaults to gl.RGBA + * + * @member {Number} + */ + this.format = format || gl.RGBA; - /** - * The width of texture - * - * @member {Number} - */ - this.width = width || -1; - /** - * The height of texture - * - * @member {Number} - */ - this.height = height || -1; + /** + * The gl type of the texture. defaults to gl.UNSIGNED_BYTE + * + * @member {Number} + */ + this.type = type || gl.UNSIGNED_BYTE; + } - /** - * The pixel format of the texture. defaults to gl.RGBA - * - * @member {Number} - */ - this.format = format || gl.RGBA; + /** + * Uploads this texture to the GPU + * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture + */ + upload(source) + { + this.bind(); - /** - * The gl type of the texture. defaults to gl.UNSIGNED_BYTE - * - * @member {Number} - */ - this.type = type || gl.UNSIGNED_BYTE; + const gl = this.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -}; + const newWidth = source.videoWidth || source.width; + const newHeight = source.videoHeight || source.height; -/** - * Uploads this texture to the GPU - * @param source {HTMLImageElement|ImageData|HTMLVideoElement} the source image of the texture - */ -Texture.prototype.upload = function(source) -{ - this.bind(); + if (newHeight !== this.height || newWidth !== this.width) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); + } - var gl = this.gl; + // if the source is a video, we need to use the videoWidth / videoHeight + // properties as width / height will be incorrect. + this.width = newWidth; + this.height = newHeight; + } + /** + * Use a data source and uploads this texture to the GPU + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + uploadData(data, width, height) + { + this.bind(); - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + const gl = this.gl; - var newWidth = source.videoWidth || source.width; - var newHeight = source.videoHeight || source.height; + if (data instanceof Float32Array) + { + if (!FLOATING_POINT_AVAILABLE) + { + const ext = gl.getExtension('OES_texture_float'); - if(newHeight !== this.height || newWidth !== this.width) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, source); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.format, this.type, source); - } + if (ext) + { + FLOATING_POINT_AVAILABLE = true; + } + else + { + throw new Error('floating point textures not available'); + } + } - // if the source is a video, we need to use the videoWidth / videoHeight properties as width / height will be incorrect. - this.width = newWidth; - this.height = newHeight; + this.type = gl.FLOAT; + } + else + { + // TODO support for other types + this.type = this.type || gl.UNSIGNED_BYTE; + } -}; + // what type of data? + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); -var FLOATING_POINT_AVAILABLE = false; + if (width !== this.width || height !== this.height) + { + gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); + } + else + { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); + } -/** - * Use a data source and uploads this texture to the GPU - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.prototype.uploadData = function(data, width, height) -{ - this.bind(); + this.width = width; + this.height = height; + } - var gl = this.gl; + /** + * Binds the texture + * @param location + */ + bind(location) + { + const gl = this.gl; + if (location !== undefined) + { + gl.activeTexture(gl.TEXTURE0 + location); + } - if(data instanceof Float32Array) - { - if(!FLOATING_POINT_AVAILABLE) - { - var ext = gl.getExtension("OES_texture_float"); + gl.bindTexture(gl.TEXTURE_2D, this.texture); + } - if(ext) - { - FLOATING_POINT_AVAILABLE = true; - } - else - { - throw new Error('floating point textures not available'); - } - } + /** + * Unbinds the texture + */ + unbind() + { + const gl = this.gl; - this.type = gl.FLOAT; - } - else - { - // TODO support for other types - this.type = this.type || gl.UNSIGNED_BYTE; - } + gl.bindTexture(gl.TEXTURE_2D, null); + } - // what type of data? - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, this.premultiplyAlpha); + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + minFilter(linear) + { + const gl = this.gl; + this.bind(); - if(width !== this.width || height !== this.height) - { - gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, this.type, data || null); - } - else - { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, this.format, this.type, data || null); - } + if (this.mipmap) + { + /* eslint-disable max-len */ + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + } + else + { + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } + } - this.width = width; - this.height = height; + /** + * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation + */ + magFilter(linear) + { + const gl = this.gl; + this.bind(); -// texSubImage2D -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); + } -/** - * Binds the texture - * @param location - */ -Texture.prototype.bind = function(location) -{ - var gl = this.gl; + /** + * Enables mipmapping + */ + enableMipmap() + { + const gl = this.gl; - if(location !== undefined) - { - gl.activeTexture(gl.TEXTURE0 + location); - } + this.bind(); - gl.bindTexture(gl.TEXTURE_2D, this.texture); -}; + this.mipmap = true; -/** - * Unbinds the texture - */ -Texture.prototype.unbind = function() -{ - var gl = this.gl; - gl.bindTexture(gl.TEXTURE_2D, null); -}; + gl.generateMipmap(gl.TEXTURE_2D); + } -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.minFilter = function( linear ) -{ - var gl = this.gl; + /** + * Enables linear filtering + */ + enableLinearScaling() + { + this.minFilter(true); + this.magFilter(true); + } - this.bind(); + /** + * Enables nearest neighbour interpolation + */ + enableNearestScaling() + { + this.minFilter(false); + this.magFilter(false); + } - if(this.mipmap) - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - } - else - { - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, linear ? gl.LINEAR : gl.NEAREST); - } -}; + /** + * Enables clamping on the texture so WebGL will not repeat it + */ + enableWrapClamp() + { + const gl = this.gl; -/** - * @param linear {Boolean} if we want to use linear filtering or nearest neighbour interpolation - */ -Texture.prototype.magFilter = function( linear ) -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + } - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, linear ? gl.LINEAR : gl.NEAREST); -}; + enableWrapRepeat() + { + const gl = this.gl; -/** - * Enables mipmapping - */ -Texture.prototype.enableMipmap = function() -{ - var gl = this.gl; + this.bind(); - this.bind(); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); + } - this.mipmap = true; + enableWrapMirrorRepeat() + { + const gl = this.gl; - gl.generateMipmap(gl.TEXTURE_2D); -}; + this.bind(); -/** - * Enables linear filtering - */ -Texture.prototype.enableLinearScaling = function() -{ - this.minFilter(true); - this.magFilter(true); -}; + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); + } -/** - * Enables nearest neighbour interpolation - */ -Texture.prototype.enableNearestScaling = function() -{ - this.minFilter(false); - this.magFilter(false); -}; + /** + * Destroys this texture + */ + destroy() + { + const gl = this.gl; + // TODO -/** - * Enables clamping on the texture so WebGL will not repeat it - */ -Texture.prototype.enableWrapClamp = function() -{ - var gl = this.gl; + gl.deleteTexture(this.texture); + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param source {HTMLImageElement|ImageData} the source image of the texture + * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha + */ + static fromSource(gl, source, premultiplyAlpha) + { + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); -}; + texture.premultiplyAlpha = premultiplyAlpha || false; + texture.upload(source); -/** - * Enable tiling on the texture - */ -Texture.prototype.enableWrapRepeat = function() -{ - var gl = this.gl; + return texture; + } - this.bind(); + /** + * @static + * @param gl {WebGLRenderingContext} The current WebGL context + * @param data {TypedArray} the data to upload to the texture + * @param width {number} the new width of the texture + * @param height {number} the new height of the texture + */ + static fromData(gl, data, width, height) + { + // console.log(data, width, height); + const texture = new Texture(gl); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); -}; + texture.uploadData(data, width, height); -Texture.prototype.enableWrapMirrorRepeat = function() -{ - var gl = this.gl; - - this.bind(); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT); -}; - - -/** - * Destroys this texture - */ -Texture.prototype.destroy = function() -{ - var gl = this.gl; - //TODO - gl.deleteTexture(this.texture); -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param source {HTMLImageElement|ImageData} the source image of the texture - * @param premultiplyAlpha {Boolean} If we want to use pre-multiplied alpha - */ -Texture.fromSource = function(gl, source, premultiplyAlpha) -{ - var texture = new Texture(gl); - texture.premultiplyAlpha = premultiplyAlpha || false; - texture.upload(source); - - return texture; -}; - -/** - * @static - * @param gl {WebGLRenderingContext} The current WebGL context - * @param data {TypedArray} the data to upload to the texture - * @param width {number} the new width of the texture - * @param height {number} the new height of the texture - */ -Texture.fromData = function(gl, data, width, height) -{ - //console.log(data, width, height); - var texture = new Texture(gl); - texture.uploadData(data, width, height); - - return texture; -}; - - -module.exports = Texture; + return texture; + } +} diff --git a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js index aff6b01..b650168 100644 --- a/src/core/renderers/webgl/systems/textures/TextureGCSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureGCSystem.js @@ -9,7 +9,7 @@ * @class * @memberof PIXI */ -export default class TextureGCSystem extends WebGLSystem +export default class TextureGCSystem extends WebGLSystem { /** * @param {PIXI.WebGLRenderer} renderer - The renderer this System works for. @@ -25,7 +25,6 @@ this.mode = settings.GC_MODE; } - /** * Checks to see when the last time a texture was used * if the texture has not been used for a specified amount of time it will be removed from the GPU diff --git a/src/core/renderers/webgl/systems/textures/TextureSystem.js b/src/core/renderers/webgl/systems/textures/TextureSystem.js index b7fef02..37036a9 100644 --- a/src/core/renderers/webgl/systems/textures/TextureSystem.js +++ b/src/core/renderers/webgl/systems/textures/TextureSystem.js @@ -34,13 +34,12 @@ null, null, null, - null + null, ]; this.currentLocation = -1; this.managedTextures = []; - } /** @@ -51,54 +50,56 @@ contextChange() { const gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {} + this.emptyTextures = {}; this.emptyTextures[gl.TEXTURE_2D] = new GLTexture.fromData(this.gl, null, 1, 1); this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(this.gl); gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) + let i; + + for (i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); } gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { + for (i = 0; i < this.boundTextures.length; i++) + { this.bind(null, i); } } bind(texture, location) { - const gl = this.gl; - location = location || 0; - if(this.currentLocation !== location) + if (this.currentLocation !== location) { this.currentLocation = location; gl.activeTexture(gl.TEXTURE0 + location); } - if(texture) + if (texture) { texture = texture.baseTexture || texture; - if(texture.valid) + if (texture.valid) { - const glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + gl.bindTexture(texture.target, glTexture.texture); - if(glTexture.dirtyId !== texture.dirtyId) + if (glTexture.dirtyId !== texture.dirtyId) { glTexture.dirtyId = texture.dirtyId; this.updateTexture(texture); @@ -118,11 +119,11 @@ { const gl = this.gl; - for (var i = 0; i < this.boundTextures.length; i++) { - - if(this.boundTextures[i] === texture) + for (let i = 0; i < this.boundTextures.length; i++) + { + if (this.boundTextures[i] === texture) { - if(this.currentLocation !== i) + if (this.currentLocation !== i) { gl.activeTexture(gl.TEXTURE0 + i); this.currentLocation = i; @@ -136,9 +137,8 @@ initTexture(texture) { - const gl = this.gl; + const glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); - var glTexture = new GLTexture(this.gl, -1, -1, texture.format, texture.type); glTexture.premultiplyAlpha = texture.premultiplyAlpha; // guarentee an update.. glTexture.dirtyId = -1; @@ -156,22 +156,24 @@ const glTexture = texture._glTextures[this.CONTEXT_UID]; const gl = this.gl; + let i; + let texturePart; + // TODO there are only 3 textures as far as im aware? // Cube / 2D and later 3d. (the latter is WebGL2, we will get to that soon!) - if(texture.target === gl.TEXTURE_CUBE_MAP) + if (texture.target === gl.TEXTURE_CUBE_MAP) { // console.log( gl.UNSIGNED_BYTE) - for (var i = 0; i < texture.sides.length; i++) + for (i = 0; i < texture.sides.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.sides[i]; + texturePart = texture.sides[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.uploadable) + if (texturePart.resource.uploadable) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + texturePart.side, 0, texture.format, @@ -206,7 +208,7 @@ } } } - else if(texture.target === gl.TEXTURE_2D_ARRAY) + else if (texture.target === gl.TEXTURE_2D_ARRAY) { gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, @@ -219,21 +221,21 @@ texture.type, null); - for (var i = 0; i < texture.array.length; i++) + for (i = 0; i < texture.array.length; i++) { // TODO - we should only upload what changed.. // but im sure this is not going to be a problem just yet! - var texturePart = texture.array[i]; + texturePart = texture.array[i]; - if(texturePart.resource) + if (texturePart.resource) { - if(texturePart.resource.loaded) + if (texturePart.resource.loaded) { gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, - 0,//xoffset - 0,//yoffset - i,//zoffset + 0, // xoffset + 0, // yoffset + i, // zoffset texturePart.resource.width, texturePart.resource.height, 1, @@ -245,24 +247,21 @@ } } else - { - if(texture.resource) + if (texture.resource) { - if(texture.resource.uploadable) + if (texture.resource.uploadable) { - glTexture.upload(texture.resource.source); - - } - else - { - glTexture.uploadData(texture.resource.source, texture.width, texture.height); - } + glTexture.upload(texture.resource.source); } else - { - glTexture.uploadData(null, texture.width, texture.height); + { + glTexture.uploadData(texture.resource.source, texture.width, texture.height); } } + else + { + glTexture.uploadData(null, texture.width, texture.height); + } // lets only update what changes.. this.setStyle(texture); @@ -306,9 +305,11 @@ gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, texture.wrapMode); gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, texture.wrapMode); - if(texture.mipmap) + if (texture.mipmap) { + /* eslint-disable max-len */ gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ } else { @@ -317,4 +318,4 @@ gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST); } -} \ No newline at end of file +} diff --git a/src/core/renderers/webgl/utils/Quad.js b/src/core/renderers/webgl/utils/Quad.js index e7b0d05..5ecd23e 100644 --- a/src/core/renderers/webgl/utils/Quad.js +++ b/src/core/renderers/webgl/utils/Quad.js @@ -1,6 +1,6 @@ -import glCore from 'pixi-gl-core'; import createIndicesForQuads from '../../../utils/createIndicesForQuads'; -import Geometry from '../../../geometry/Geometry' +import Geometry from '../../../geometry/Geometry'; + /** * Helper class to create a quad * @@ -51,7 +51,6 @@ this.interleaved[(i * 4) + 3] = this.uvs[(i * 2) + 1]; } - /* * @member {Uint16Array} An array containing the indices of the vertices * @@ -92,7 +91,6 @@ */ initVao(shader) { - return; this.vao.clear() .addIndex(this.indexBuffer) .addAttribute(this.vertexBuffer, shader.attributes.aVertexPosition, this.gl.FLOAT, false, 4 * 4, 0) @@ -148,10 +146,9 @@ */ upload() { - this.getAttribute('aVertexPosition').update(); - this.getAttribute('aTextureCoord').update(); + this.getAttribute('aVertexPosition').update(); + this.getAttribute('aTextureCoord').update(); - return; for (let i = 0; i < 4; i++) { this.interleaved[i * 4] = this.vertices[(i * 2)]; diff --git a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js index 3544cb9..c5fb6b5 100644 --- a/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js +++ b/src/core/renderers/webgl/utils/checkMaxIfStatmentsInShader.js @@ -1,5 +1,3 @@ -import glCore from 'pixi-gl-core'; - const fragTemplate = [ 'precision mediump float;', 'void main(void){', diff --git a/src/core/shader/Program.js b/src/core/shader/Program.js index c5d09cd..d16de5e 100644 --- a/src/core/shader/Program.js +++ b/src/core/shader/Program.js @@ -1,6 +1,5 @@ import extractUniformsFromSrc from './extractUniformsFromSrc'; -import generateUniformsSync from './generateUniformsSync'; -import shaderUtils from '../renderers/webgl/systems/shader/shader'; +import * as shaderUtils from '../renderers/webgl/systems/shader/shader'; import { ProgramCache } from '../utils'; import getTestContext from '../utils/getTestContext'; @@ -39,7 +38,7 @@ // this is where we store shader references.. this.glShaders = {}; - this.syncUniforms = null;//generateUniformsSync(this.uniformData); + this.syncUniforms = null; this.id = UID++; } @@ -71,7 +70,7 @@ this.attributeData = this.getAttributeData(program, gl); this.uniformData = this.getUniformData(program, gl); - //gl.deleteProgram(program); + // gl.deleteProgram(program); } } @@ -136,7 +135,7 @@ // TODO expose this as a prop? // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - //const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); + // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); for (let i = 0; i < totalUniforms; i++) { @@ -146,17 +145,14 @@ const isArray = uniformData.name.match(/\[.*?\]/, ''); const type = shaderUtils.mapType(gl, uniformData.type); - // if (!name.match(maskRegex)) - { - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray:isArray, - value: shaderUtils.defaultValue(type, uniformData.size), - }; - /*eslint-enable */ - } + /*eslint-disable */ + uniforms[name] = { + type: type, + size: uniformData.size, + isArray:isArray, + value: shaderUtils.defaultValue(type, uniformData.size), + }; + /*eslint-enable */ } return uniforms; diff --git a/src/core/shader/Shader.js b/src/core/shader/Shader.js index 2f8dc56..97d59a0 100644 --- a/src/core/shader/Shader.js +++ b/src/core/shader/Shader.js @@ -19,15 +19,15 @@ // lets see whats been passed in // uniforms should be converted to a uniform group - if(uniforms) + if (uniforms) { - if(uniforms instanceof UniformGroup) + if (uniforms instanceof UniformGroup) { this.uniformGroup = uniforms; } else { - this.uniformGroup = new UniformGroup(uniforms) + this.uniformGroup = new UniformGroup(uniforms); } } else @@ -49,7 +49,7 @@ checkUniformExists(name, group) { - if(group.uniforms[name]) + if (group.uniforms[name]) { return true; } @@ -58,9 +58,9 @@ { const uniform = group.uniforms[i]; - if(uniform.group) + if (uniform.group) { - if( this.checkUniformExists(name, uniform) ) + if (this.checkUniformExists(name, uniform)) { return true; } diff --git a/src/core/shader/UniformGroup.js b/src/core/shader/UniformGroup.js index e2ed22a..c8148e3 100644 --- a/src/core/shader/UniformGroup.js +++ b/src/core/shader/UniformGroup.js @@ -1,4 +1,3 @@ - let UID = 0; // let math = require('../../../math'); diff --git a/src/core/shader/generateUniformsSync.js b/src/core/shader/generateUniformsSync.js index 8a7cf55..427777b 100644 --- a/src/core/shader/generateUniformsSync.js +++ b/src/core/shader/generateUniformsSync.js @@ -1,20 +1,18 @@ - - -//cv = CachedValue -//v = value -//ud = uniformData -//uv = uniformValue -//l = loaction +// cv = CachedValue +// v = value +// ud = uniformData +// uv = uniformValue +// l = loaction const GLSL_TO_SINGLE_SETTERS_CACHED = { - float:` + float: ` if(cv !== v) { cv.v = v; gl.uniform1f(location, v) }`, - vec2:` + vec2: ` if(cv[0] !== v[0] || cv[1] !== v[1]) { cv[0] = v[0]; @@ -22,7 +20,7 @@ gl.uniform2f(location, v[0], v[1]) }`, - vec3:` + vec3: ` if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { cv[0] = v[0]; @@ -87,13 +85,13 @@ { const data = uniformData[i]; - if(!data) + if (!data) { - if(group.uniforms[i].group) + if (group.uniforms[i].group) { func += ` renderer.shader.syncUniformGroup(uv.${i}); - ` + `; } continue; @@ -109,7 +107,9 @@ gl.uniform1f(ud.${i}.location, uv.${i}) }\n`; } - else if ( (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ + else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray) + /* eslint-disable max-len */ { func += ` renderer.texture.bind(uv.${i}, ${textureCount}); @@ -118,13 +118,13 @@ { ud.${i}.value = ${textureCount}; gl.uniform1i(ud.${i}.location, ${textureCount});\n; // eslint-disable-line max-len - }\n` + }\n`; textureCount++; } else if (data.type === 'mat3' && data.size === 1) { - if(group.uniforms[i].a !== undefined) + if (group.uniforms[i].a !== undefined) { // TODO and some smart caching dirty ids here! func += ` @@ -142,7 +142,7 @@ { // TODO - do we need both here? // maybe we can get away with only using points? - if(group.uniforms[i].x !== undefined) + if (group.uniforms[i].x !== undefined) { func += ` cv = ud.${i}.value; diff --git a/src/core/sprites/webgl/SpriteRenderer.js b/src/core/sprites/webgl/SpriteRenderer.js index 57b4b3c..57331df 100644 --- a/src/core/sprites/webgl/SpriteRenderer.js +++ b/src/core/sprites/webgl/SpriteRenderer.js @@ -1,6 +1,5 @@ import ObjectRenderer from '../../renderers/webgl/utils/ObjectRenderer'; import WebGLRenderer from '../../renderers/webgl/WebGLRenderer'; -import GLBuffer from '../../renderers/webgl/systems/geometry/GLBuffer'; import createIndicesForQuads from '../../utils/createIndicesForQuads'; import generateMultiTextureShader from './generateMultiTextureShader'; import checkMaxIfStatmentsInShader from '../../renderers/webgl/utils/checkMaxIfStatmentsInShader'; @@ -8,12 +7,11 @@ import settings from '../../settings'; import bitTwiddle from 'bit-twiddle'; import Geometry from '../../geometry/Geometry'; -//TODO rename this -import Buffer_GEOM from '../../geometry/Buffer'; - +// TODO rename this +import GeometryBuffer from '../../geometry/Buffer'; let TICK = 0; -let TEXTURE_TICK = 0; +// const TEXTURE_TICK = 0; /** * Renderer dedicated to drawing and batching sprites. @@ -69,7 +67,7 @@ * @member {Uint16Array} */ this.indices = createIndicesForQuads(this.size); - this.indexBuffer = new Buffer_GEOM(this.indices, true, true); + this.indexBuffer = new GeometryBuffer(this.indices, true, true); /** * The default shaders that is used if a sprite doesn't have a more specific one. @@ -120,7 +118,6 @@ this.MAX_TEXTURES = checkMaxIfStatmentsInShader(this.MAX_TEXTURES, gl); } - // generate generateMultiTextureProgram, may be a better move? this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES); @@ -128,15 +125,15 @@ // as it is not used by the shader so is optimized out. for (let i = 0; i < this.vaoMax; i++) { - var buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[i] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[i] = buffer; @@ -203,7 +200,7 @@ const float32View = buffer.float32View; const uint32View = buffer.uint32View; - const touch = 0;//this.renderer.textureGC.count; + // const touch = 0;// this.renderer.textureGC.count; let index = 0; let nextTexture; @@ -231,29 +228,28 @@ // upload the sprite elemetns... // they have all ready been calculated so we just need to push them into the buffer. - var sprite = sprites[i]; + const sprite = sprites[i]; nextTexture = sprite._texture.baseTexture; textureId = nextTexture._id; - - if(blendMode !== sprite.blendMode) + if (blendMode !== sprite.blendMode) { blendMode = sprite.blendMode; // force the batch to break! currentTexture = null; - textureCount = this.MAX_TEXTURES; + textureCount = MAX_TEXTURES; TICK++; } - if(currentTexture !== nextTexture) + if (currentTexture !== nextTexture) { currentTexture = nextTexture; - if(nextTexture._enabled !== TICK) + if (nextTexture._enabled !== TICK) { - if(textureCount === this.MAX_TEXTURES) + if (textureCount === MAX_TEXTURES) { TICK++; @@ -273,7 +269,6 @@ currentGroup.textures[currentGroup.textureCount++] = nextTexture; textureCount++; } - } vertexData = sprite.vertexData; @@ -345,15 +340,15 @@ { this.vaoMax++; - let buffer = new Buffer_GEOM(null, false); + const buffer = new GeometryBuffer(null, false); /* eslint-disable max-len */ this.vaos[this.vertexCount] = new Geometry() - .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) - .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) - .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) - .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) - .addIndex(this.indexBuffer) + .addAttribute('aVertexPosition', buffer, 2, false, gl.FLOAT) + .addAttribute('aTextureCoord', buffer, 2, true, gl.UNSIGNED_SHORT) + .addAttribute('aColor', buffer, 4, true, gl.UNSIGNED_BYTE) + .addAttribute('aTextureId', buffer, 1, true, gl.FLOAT) + .addIndex(this.indexBuffer); /* eslint-enable max-len */ this.vertexBuffers[this.vertexCount] = buffer; @@ -372,19 +367,19 @@ this.renderer.geometry.updateBuffers(); } - /// render the groups.. - for (i = 0; i < groupCount; i++) { + // / render the groups.. + for (i = 0; i < groupCount; i++) +{ + const group = groups[i]; + const groupTextureCount = group.textureCount; - var group = groups[i]; - var groupTextureCount = group.textureCount; - - for (var j = 0; j < groupTextureCount; j++) + for (let j = 0; j < groupTextureCount; j++) { this.renderer.texture.bind(group.textures[j], j); } // set the blend mode.. - this.renderer.state.setBlendMode( group.blend ); + this.renderer.state.setBlendMode(group.blend); gl.drawElements(gl.TRIANGLES, group.size * 6, gl.UNSIGNED_SHORT, group.start * 6 * 2); } diff --git a/src/core/sprites/webgl/generateMultiTextureShader.js b/src/core/sprites/webgl/generateMultiTextureShader.js index cab5255..6d434dc 100644 --- a/src/core/sprites/webgl/generateMultiTextureShader.js +++ b/src/core/sprites/webgl/generateMultiTextureShader.js @@ -1,6 +1,5 @@ import Shader from '../../shader/Shader'; import UniformGroup from '../../shader/UniformGroup'; -import { PRECISION } from '../../const'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -28,9 +27,8 @@ } const uniforms = { - default:UniformGroup.from({uSamplers:sampleValues}, true), - } - + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; const vertexSrc = readFileSync(join(__dirname, './texture.vert'), 'utf8'); let fragmentSrc = fragTemplate; @@ -38,7 +36,7 @@ fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures); fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures)); - const shader = Shader.from(vertexSrc, fragmentSrc, uniforms);//, PRECISION.DEFAULT); + const shader = Shader.from(vertexSrc, fragmentSrc, uniforms); return shader; } diff --git a/src/core/text/Text.js b/src/core/text/Text.js index 32d9c46..caaf4a9 100644 --- a/src/core/text/Text.js +++ b/src/core/text/Text.js @@ -43,7 +43,7 @@ canvas.width = 3; canvas.height = 3; - const texture = Texture.fromCanvas(canvas, settings.SCALE_MODE, 'text'); + const texture = Texture.from(canvas, settings.SCALE_MODE, 'text'); texture.orig = new Rectangle(); texture.trim = new Rectangle(); @@ -344,7 +344,7 @@ // call sprite onTextureUpdate to update scale if _width or _height were set this._onTextureUpdate(); - texture.baseTexture.update();//emit('update', texture.baseTexture); + texture.baseTexture.update();// emit('update', texture.baseTexture); this.dirty = false; } diff --git a/src/core/textures/ArrayTexture.js b/src/core/textures/ArrayTexture.js index e609fe3..6a7d0a7 100644 --- a/src/core/textures/ArrayTexture.js +++ b/src/core/textures/ArrayTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class ArrayTexture extends Texture { @@ -16,41 +16,41 @@ setResource(resource, index) { - var layer = this.array[index]; - if(!layer) + let layer = this.array[index]; + + if (!layer) { - layer = this.array[index] = {index:index, texture:this, resource:null, texturePart:true, dirtyId:0}; + layer = this.array[index] = { index, texture: this, resource: null, texturePart: true, dirtyId: 0 }; } layer.resource = resource; - resource.load.then((resource) => { - - if(layer.resource === resource) + resource.load.then((resource) => +{ + if (layer.resource === resource) { this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.array) + if (this.array) { - for (var i = 0; i < this.array.length; i++) { - + for (let i = 0; i < this.array.length; i++) +{ const layer = this.array[i]; - if(layer.resource && !layer.resource.loaded) + if (layer.resource && !layer.resource.loaded) { valid = false; break; @@ -63,13 +63,13 @@ static from(width, height, ...urls) { - var arrayTexture = new ArrayTexture(width, height); + const arrayTexture = new ArrayTexture(width, height); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { arrayTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return arrayTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/BaseRenderTexture.js b/src/core/textures/BaseRenderTexture.js index 3e4e0cb..025e96d 100644 --- a/src/core/textures/BaseRenderTexture.js +++ b/src/core/textures/BaseRenderTexture.js @@ -1,6 +1,5 @@ import BaseTexture from './BaseTexture'; import FrameBuffer from './FrameBuffer'; -import settings from '../settings'; /** * A BaseRenderTexture is a special texture that allows any Pixi display object to be rendered to it. @@ -71,17 +70,26 @@ */ this._canvasRenderTarget = null; - this.clearColor = [0,0,0,0]; + this.clearColor = [0, 0, 0, 0]; this.frameBuffer = new FrameBuffer(width, height) .addColorTexture(0, this); + // TODO - could this be added the systems? + /** * The data structure for the stencil masks * * @member {PIXI.Graphics[]} */ this.stencilMaskStack = []; + + /** + * The data structure for the filters + * + * @member {PIXI.Graphics[]} + */ + this.filterStack = []; } /** diff --git a/src/core/textures/BaseTexture.js b/src/core/textures/BaseTexture.js index 13417a1..553384d 100644 --- a/src/core/textures/BaseTexture.js +++ b/src/core/textures/BaseTexture.js @@ -1,14 +1,9 @@ import { - uid, getUrlFileExtension, decomposeDataUri, getSvgSize, - getResolutionOfUrl, BaseTextureCache, TextureCache, + uid, BaseTextureCache, TextureCache, } from '../utils'; -import {FORMATS, TARGETS, TYPES, SCALE_MODES} from '../const'; -import ImageResource from './resources/ImageResource'; +import { FORMATS, TARGETS, TYPES, SCALE_MODES } from '../const'; import BufferResource from './resources/BufferResource'; -import CanvasResource from './resources/CanvasResource'; -import SVGResource from './resources/SVGResource'; -import VideoResource from './resources/VideoResource'; import createResource from './resources/createResource'; import settings from '../settings'; @@ -17,7 +12,7 @@ export default class BaseTexture extends EventEmitter { - constructor(resource, scaleMode, resolution, width, height, format, type, mipmap) + constructor(resource, scaleMode, resolution, width, height, format, type, mipmap = settings.MIPMAP_TEXTURES) { super(); @@ -60,7 +55,9 @@ * * @member {Boolean} */ - this.mipmap = false;//settings.MIPMAP_TEXTURES; + // TODO fix mipmapping.. + mipmap = false; + this.mipmap = mipmap; /** * Set to true to enable pre-multiplied alpha @@ -90,7 +87,7 @@ * @member {Number} */ this.format = format || FORMATS.RGBA; - this.type = type || TYPES.UNSIGNED_BYTE; //UNSIGNED_BYTE + this.type = type || TYPES.UNSIGNED_BYTE; // UNSIGNED_BYTE this.target = TARGETS.TEXTURE_2D; // gl.TEXTURE_2D @@ -104,7 +101,7 @@ this.resource = null; - if(resource) + if (resource) { // lets convert this to a resource.. resource = createResource(resource); @@ -170,7 +167,7 @@ { const resource = this.resource; - if(resource && resource.width !== -1 && resource.hight !== -1) + if (resource && resource.width !== -1 && resource.hight !== -1) { this.width = resource.width / this.resolution; this.height = resource.height / this.resolution; @@ -181,41 +178,38 @@ { // TODO currently a resource can only be set once.. - if(this.resource) + if (this.resource) { this.resource.resourceUpdated.remove(this); } - this.resource = resource; - resource.resourceUpdated.add(this); //calls resourceUpaded + resource.resourceUpdated.add(this); // calls resourceUpaded - if(resource.loaded) + if (resource.loaded) { - this.resourceLoaded(resource) + this.resourceLoaded(resource); } resource.load .then(this.resourceLoaded.bind(this)) - .catch((reason)=>{ - + .catch((reason) => + { // failed to load - maybe resource was destroyed before it loaded. console.warn(reason); - - }) - + }); } resourceLoaded(resource) { - if(this.resource === resource) + if (this.resource === resource) { this.updateResolution(); this.validate(); - if(this.valid) + if (this.valid) { this.isPowerOfTwo = bitTwiddle.isPow2(this.realWidth) && bitTwiddle.isPow2(this.realHeight); @@ -225,7 +219,6 @@ this.emit('loaded', this); } } - } resourceUpdated() @@ -251,7 +244,7 @@ { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } @@ -285,7 +278,7 @@ // remove and destroy the resource - if(this.resource) + if (this.resource) { this.resource.destroy(); this.resource = null; @@ -320,9 +313,9 @@ * @param {number} [sourceScale=(auto)] - Scale for the original image, used with Svg images. * @return {PIXI.BaseTexture} The new base texture. */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -330,7 +323,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -342,7 +335,7 @@ if (!baseTexture) { - baseTexture = new BaseTexture(source); + baseTexture = new BaseTexture(source, scaleMode); baseTexture.cacheId = cacheId; BaseTexture.addToCache(baseTexture, cacheId); } @@ -352,29 +345,31 @@ static fromFloat32Array(width, height, float32Array) { - float32Array = float32Array || new Float32Array(width*height*4); + float32Array = float32Array || new Float32Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(float32Array), + const texture = new BaseTexture(new BufferResource(float32Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.FLOAT); + return texture; } static fromUint8Array(width, height, uint8Array) { - uint8Array = uint8Array || new Uint8Array(width*height*4); + uint8Array = uint8Array || new Uint8Array(width * height * 4); - var texture = new BaseTexture(new BufferResource(uint8Array), + const texture = new BaseTexture(new BufferResource(uint8Array), SCALE_MODES.NEAREST, 1, width, height, FORMATS.RGBA, TYPES.UNSIGNED_BYTE); + return texture; } @@ -453,4 +448,4 @@ BaseTexture.fromFrame = BaseTexture.fromFrame; BaseTexture.fromImage = BaseTexture.from; BaseTexture.fromSVG = BaseTexture.from; -BaseTexture.fromCanvas = BaseTexture.from; \ No newline at end of file +BaseTexture.fromCanvas = BaseTexture.from; diff --git a/src/core/textures/CubeTexture.js b/src/core/textures/CubeTexture.js index 5a66a1f..1eeccd3 100644 --- a/src/core/textures/CubeTexture.js +++ b/src/core/textures/CubeTexture.js @@ -1,6 +1,6 @@ import Texture from './BaseTexture'; import ImageResource from './resources/ImageResource'; -import {TARGETS} from './../const'; +import { TARGETS } from './../const'; export default class CubeTexture extends Texture { @@ -12,57 +12,57 @@ this.resources = []; - this.positiveX = {side:0, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeX = {side:1, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveX = { side: 0, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeX = { side: 1, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveY = {side:2, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeY = {side:3, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveY = { side: 2, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeY = { side: 3, texture: this, resource: null, texturePart: true, dirtyId: 0 }; - this.positiveZ = {side:4, texture:this, resource:null, texturePart:true, dirtyId:0}; - this.negativeZ = {side:5, texture:this, resource:null, texturePart:true, dirtyId:0}; + this.positiveZ = { side: 4, texture: this, resource: null, texturePart: true, dirtyId: 0 }; + this.negativeZ = { side: 5, texture: this, resource: null, texturePart: true, dirtyId: 0 }; this.sides = [this.positiveX, this.negativeX, - this.positiveY, this.negativeY, - this.positiveZ, this.negativeZ]; + this.positiveY, this.negativeY, + this.positiveZ, this.negativeZ]; } setResource(resource, index) { - var side = this.sides[index]; + const side = this.sides[index]; + side.resource = resource; - resource.load.then((resource) => { - - if(side.resource === resource) + resource.load.then((resource) => +{ + if (side.resource === resource) { this.width = resource.width; this.height = resource.height; // we have not swapped half way! - //side.dirtyId++; + // side.dirtyId++; this.validate(); this.dirtyId++; } - - }) + }); } validate() { let valid = true; - if(this.width === -1 || this.height === -1) + if (this.width === -1 || this.height === -1) { valid = false; } - if(this.sides) + if (this.sides) { - for (var i = 0; i < this.sides.length; i++) { - + for (let i = 0; i < this.sides.length; i++) +{ const side = this.sides[i]; - if(side.resource && !side.resource.loaded) + if (side.resource && !side.resource.loaded) { valid = false; break; @@ -70,19 +70,18 @@ } } - this.valid = valid; } static from(...urls) { - var cubeTexture = new CubeTexture(); + const cubeTexture = new CubeTexture(); - for (var i = 0; i < 6; i++) + for (let i = 0; i < 6; i++) { cubeTexture.setResource(ImageResource.from(urls[i % urls.length]), i); } return cubeTexture; } -} \ No newline at end of file +} diff --git a/src/core/textures/FrameBuffer.js b/src/core/textures/FrameBuffer.js index 0d8796b..ae45fb9 100644 --- a/src/core/textures/FrameBuffer.js +++ b/src/core/textures/FrameBuffer.js @@ -1,91 +1,93 @@ -import Texture from './BaseTexture' -import {FORMATS, TYPES} from './../const'; +import Texture from './BaseTexture'; +import { FORMATS, TYPES } from './../const'; export default class FrameBuffer { constructor(width, height) { - this.width = width || 100; - this.height = height || 100; + this.width = width || 100; + this.height = height || 100; - this.stencil = false; + this.stencil = false; this.depth = false; this.dirtyId = 0; this.dirtyFormat = 0; - this.dirtySize = 0; + this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; + this.depthTexture = null; + this.colorTextures = []; - this.glFrameBuffers = {}; + this.glFrameBuffers = {}; } get colorTexture() { - return this.colorTextures[0]; + return this.colorTextures[0]; } addColorTexture(index, texture) { // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); - - this.dirtyId++; - this.dirtyFormat++; - - return this; - } - - - addDepthTexture(texture) - { - this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);//UNSIGNED_SHORT; + this.colorTextures[index || 0] = texture || new Texture(null, 0, 1, this.width, this.height);// || new Texture(); this.dirtyId++; this.dirtyFormat++; - return this; + + return this; + } + + addDepthTexture(texture) + { + /* eslint-disable max-len */ + this.depthTexture = texture || new Texture(null, 0, 1, this.width, this.height, FORMATS.DEPTH_COMPONENT, TYPES.UNSIGNED_SHORT);// UNSIGNED_SHORT; + /* eslint-disable max-len */ + + this.dirtyId++; + this.dirtyFormat++; + + return this; } enableDepth() { - this.depth = true; + this.depth = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } enableStencil() { - this.stencil = true; + this.stencil = true; this.dirtyId++; - this.dirtyFormat++; + this.dirtyFormat++; - return this; + return this; } resize(width, height) { - if(width === this.width && height === this.height)return; + if (width === this.width && height === this.height) return; - this.width = width; - this.height = height; + this.width = width; + this.height = height; - this.dirtyId++; + this.dirtyId++; this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { + for (let i = 0; i < this.colorTextures.length; i++) + { this.colorTextures[i].resize(width, height); } - if(this.depthTexture) + if (this.depthTexture) { - this.depthTexture.resize(width, height) + this.depthTexture.resize(width, height); } } - -} \ No newline at end of file +} diff --git a/src/core/textures/Spritesheet.js b/src/core/textures/Spritesheet.js index dc35fd9..3b14078 100644 --- a/src/core/textures/Spritesheet.js +++ b/src/core/textures/Spritesheet.js @@ -113,7 +113,7 @@ { this.baseTexture.resolution = resolution; this.baseTexture.updateResolution(); - //this.baseTexture.update(); + // this.baseTexture.update(); } return resolution; diff --git a/src/core/textures/Texture.js b/src/core/textures/Texture.js index 609d87c..108c862 100644 --- a/src/core/textures/Texture.js +++ b/src/core/textures/Texture.js @@ -1,12 +1,11 @@ import BaseTexture from './BaseTexture'; -import VideoBaseTexture from './VideoBaseTexture'; import ImageResource from './resources/ImageResource'; import CanvasResource from './resources/CanvasResource'; import TextureUvs from './TextureUvs'; import EventEmitter from 'eventemitter3'; import settings from '../settings'; import { Rectangle } from '../math'; -import { TextureCache, BaseTextureCache, getResolutionOfUrl } from '../utils'; +import { uid, TextureCache, getResolutionOfUrl } from '../utils'; /** * A texture stores the information that represents an image or part of an image. It cannot be added @@ -269,95 +268,6 @@ } /** - * Helper function that creates a Texture object from the given image url. - * If the image is not in the texture cache it will be created and loaded. - * - * @static - * @param {string} imageUrl - The image url of the texture - * @param {boolean} [crossorigin] - Whether requests should be treated as crossorigin - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [sourceScale=(auto)] - Scale for the original image, used with SVG images. - * @return {PIXI.Texture} The newly created texture - */ - static fromImage(imageUrl, crossorigin, scaleMode, sourceScale) - { - let texture = TextureCache[imageUrl]; - - if (!texture) - { - texture = new Texture(BaseTexture.fromImage(imageUrl, crossorigin, scaleMode, sourceScale)); - Texture.addToCache(texture, imageUrl); - } - - return texture; - } - - /** - * Helper function that creates a sprite that will contain a texture from the TextureCache based on the frameId - * The frame ids are created when a Texture packer file has been loaded - * - * @static - * @param {string} frameId - The frame Id of the texture in the cache - * @return {PIXI.Texture} The newly created texture - */ - static fromFrame(frameId) - { - const texture = TextureCache[frameId]; - - if (!texture) - { - throw new Error(`The frameId "${frameId}" does not exist in the texture cache`); - } - - return texture; - } - - /** - * Helper function that creates a new Texture based on the given canvas element. - * - * @static - * @param {HTMLCanvasElement} canvas - The canvas element source of the texture - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {string} [origin='canvas'] - A string origin of who created the base texture - * @return {PIXI.Texture} The newly created texture - */ - static fromCanvas(canvas, scaleMode, origin = 'canvas') - { - return new Texture(BaseTexture.fromCanvas(canvas, scaleMode, origin)); - } - - /** - * Helper function that creates a new Texture based on the given video element. - * - * @static - * @param {HTMLVideoElement|string} video - The URL or actual element of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideo(video, scaleMode) - { - if (typeof video === 'string') - { - return Texture.fromVideoUrl(video, scaleMode); - } - - return new Texture(VideoBaseTexture.fromVideo(video, scaleMode)); - } - - /** - * Helper function that creates a new Texture based on the video url. - * - * @static - * @param {string} videoUrl - URL of the video - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.Texture} The newly created texture - */ - static fromVideoUrl(videoUrl, scaleMode) - { - return new Texture(VideoBaseTexture.fromUrl(videoUrl, scaleMode)); - } - - /** * Helper function that creates a new Texture based on the source you provide. * The source can be - frame id, image url, video url, canvas element, video element, base texture * @@ -366,9 +276,9 @@ * source - Source to create texture from * @return {PIXI.Texture} The newly created texture */ - static from(source, scaleMode, sourceScale) + static from(source, scaleMode) { - var cacheId = null; + let cacheId = null; if (typeof source === 'string') { @@ -376,7 +286,7 @@ } else { - if(!source._pixiId) + if (!source._pixiId) { source._pixiId = `pixiid_${uid()}`; } @@ -388,15 +298,13 @@ if (!texture) { - texture = new Texture(new BaseTexture(source)); + texture = new Texture(new BaseTexture(source, scaleMode)); texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); Texture.addToCache(texture, cacheId); } - else - { - // console.log(texture.baseTexture.width) - } + // lets assume its a base texture! return texture; } @@ -414,7 +322,7 @@ static fromLoader(source, imageUrl, name) { // console.log('added from loader...') - const resource = new ImageResource(source);//.from(imageUrl, crossorigin);// document.createElement('img'); + const resource = new ImageResource(source);// .from(imageUrl, crossorigin);// document.createElement('img'); // console.log('base resource ' + resource.width); const baseTexture = new BaseTexture(resource, @@ -595,7 +503,6 @@ } } - Texture.fromImage = Texture.from; Texture.fromSVG = Texture.from; Texture.fromCanvas = Texture.from; diff --git a/src/core/textures/resources/BufferResource.js b/src/core/textures/resources/BufferResource.js index 8300d13..1aa1586 100644 --- a/src/core/textures/resources/BufferResource.js +++ b/src/core/textures/resources/BufferResource.js @@ -4,19 +4,18 @@ { constructor(source) { - super(source); + super(source); this.uploadable = false; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - - }) + }); } static from(array) { return new BufferResource(array); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/CanvasResource.js b/src/core/textures/resources/CanvasResource.js index 70c3962..9a1a871 100644 --- a/src/core/textures/resources/CanvasResource.js +++ b/src/core/textures/resources/CanvasResource.js @@ -6,20 +6,20 @@ { super(source); - this.loaded = true; // TODO rename to ready? + this.loaded = true; // TODO rename to ready? this.width = source.width; this.height = source.height; this.uploadable = true; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { resolve(this); - }) + }); } static from(canvas) { return new CanvasResource(canvas); } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/ImageResource.js b/src/core/textures/resources/ImageResource.js index 8ef933a..88d5531 100644 --- a/src/core/textures/resources/ImageResource.js +++ b/src/core/textures/resources/ImageResource.js @@ -7,39 +7,11 @@ { super(source); - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { const source = this.source; - source.onload = () => { - this.loaded = true; - source.onload = null; - source.onerror = null; - this.width = source.width; - this.height = source.height; - - if(window.createImageBitmap) - { - createImageBitmap(source).then((imageBitmap)=>{ - - this.source = imageBitmap; - - resolve(this); - - }) - } - else - { - resolve(this); - } - - - - } - - - - if(source.complete && source.src) + source.onload = () => { this.loaded = true; source.onload = null; @@ -47,15 +19,37 @@ this.width = source.width; this.height = source.height; - if(window.createImageBitmap) + if (window.createImageBitmap) { - createImageBitmap(source).then((imageBitmap)=>{ - + window.createImageBitmap(source).then((imageBitmap) => + { this.source = imageBitmap; resolve(this); + }); + } + else + { + resolve(this); + } + }; - }) + if (source.complete && source.src) + { + this.loaded = true; + source.onload = null; + source.onerror = null; + this.width = source.width; + this.height = source.height; + + if (window.createImageBitmap) + { + window.createImageBitmap(source).then((imageBitmap) => + { + this.source = imageBitmap; + + resolve(this); + }); } else { @@ -65,8 +59,8 @@ // source.onerror = () => { // reject('unable to load "' + source.src + '" resource cannot be found') - //} - }) + // } + }); } destroy() @@ -76,7 +70,7 @@ static from(url, crossorigin) { - var image = new Image(); + const image = new Image(); if (crossorigin === undefined && url.indexOf('data:') !== 0) { @@ -84,8 +78,8 @@ } image.src = url; + return new ImageResource(image); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/SVGResource.js b/src/core/textures/resources/SVGResource.js index 5c2aa4f..084409c 100644 --- a/src/core/textures/resources/SVGResource.js +++ b/src/core/textures/resources/SVGResource.js @@ -1,9 +1,8 @@ import { - decomposeDataUri, getSvgSize, uid + decomposeDataUri, getSvgSize, uid, } from '../../utils'; import TextureResource from './TextureResource'; - export default class SVGResource extends TextureResource { constructor(svgSource, scale) @@ -16,12 +15,11 @@ this.resolve = null; - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => +{ this.resolve = resolve; this._loadSvgSourceUsingXhr(); - - }) + }); } /** @@ -86,12 +84,12 @@ { const svgSize = getSvgSize(svgString); - // TODO do we need to wait for this to load? // seems instant! // const tempImage = new Image(); - tempImage.src = 'data:image/svg+xml,' + svgString; + + tempImage.src = `data:image/svg+xml,${svgString}`; const svgWidth = svgSize.width; const svgHeight = svgSize.height; @@ -122,10 +120,9 @@ this.resolve(this); } - static from(url, crossorigin) + static from(url) { return new SVGResource(url); } - -} \ No newline at end of file +} diff --git a/src/core/textures/resources/TextureResource.js b/src/core/textures/resources/TextureResource.js index 6f73793..7516c1e 100644 --- a/src/core/textures/resources/TextureResource.js +++ b/src/core/textures/resources/TextureResource.js @@ -4,7 +4,7 @@ { constructor(source) { - this.source = source; + this.source = source; this.loaded = false; // TODO rename to ready? @@ -21,6 +21,6 @@ destroy() { - console.warn(this, ' has no destroy function') + // somthing } -} \ No newline at end of file +} diff --git a/src/core/textures/resources/VideoResource.js b/src/core/textures/resources/VideoResource.js index 3402f96..1d6f5f8 100644 --- a/src/core/textures/resources/VideoResource.js +++ b/src/core/textures/resources/VideoResource.js @@ -1,8 +1,5 @@ import TextureResource from './TextureResource'; import * as ticker from '../../ticker'; -import { - uid -} from '../../utils'; export default class VideoResource extends TextureResource { @@ -34,7 +31,6 @@ source.addEventListener('play', this._onPlayStart.bind(this)); source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { source.addEventListener('canplay', this._onCanPlay); @@ -45,20 +41,20 @@ this._onCanPlay(); } - this.load = new Promise((resolve, reject) => { - + this.load = new Promise((resolve) => + { this.resolve = resolve; - if(this.loaded) + if (this.loaded) { this.resolve(this); } - }) + }); } update() { - //TODO - slow down and base on the videos framerate + // TODO - slow down and base on the videos framerate this.resourceUpdated.emit(); } @@ -127,7 +123,6 @@ */ _onCanPlay() { - if (this.source) { this.source.removeEventListener('canplay', this._onCanPlay); @@ -140,7 +135,7 @@ if (!this.loaded) { this.loaded = true; - if(this.resolve) + if (this.resolve) { this.resolve(this); } @@ -154,7 +149,6 @@ { this.source.play(); } - } } @@ -179,32 +173,6 @@ } /** - * Mimic Pixi BaseTexture.from.... method. - * - * @static - * @param {HTMLVideoElement} video - Video to create texture from - * @param {number} [scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @return {PIXI.VideoBaseTexture} Newly created VideoBaseTexture - */ - static fromVideo(video, scaleMode) - { - if (!video._pixiId) - { - video._pixiId = `video_${uid()}`; - } - - let baseTexture = BaseTextureCache[video._pixiId]; - - if (!baseTexture) - { - baseTexture = new VideoBaseTexture(video, scaleMode); - BaseTextureCache[video._pixiId] = baseTexture; - } - - return baseTexture; - } - - /** * Should the base texture automatically update itself, set to true by default * * @member {boolean} @@ -271,10 +239,8 @@ return new VideoResource(video, scaleMode); } - } - function createSource(path, type) { if (!type) diff --git a/src/core/textures/resources/createResource.js b/src/core/textures/resources/createResource.js index f3fa500..60fdba6 100644 --- a/src/core/textures/resources/createResource.js +++ b/src/core/textures/resources/createResource.js @@ -5,26 +5,24 @@ export default function createResource(source) { - if (typeof source === 'string') - { + if (typeof source === 'string') + { // check if its a video.. if (source.match(/\.(mp4|webm|ogg|h264|avi|mov)$/)) { - return new VideoResource.fromUrl(source); - //video! - //return Texture.fromVideoUrl(source); - //return SVGResource.from(url); + return new VideoResource.fromUrl(source); + // video! + // return Texture.fromVideoUrl(source); + // return SVGResource.from(url); } else if (source.match(/\.(svg)$/)) { // SVG return SVGResource.from(source); } - else - { + // probably an image! - return ImageResource.from(source); - } + return ImageResource.from(source); } else if (source instanceof HTMLImageElement) { @@ -38,8 +36,6 @@ { return new VideoResource(source); } - else - { - return source; - } -} \ No newline at end of file + + return source; +} diff --git a/src/core/utils/getTestContext.js b/src/core/utils/getTestContext.js index 288f12e..fd46ca4 100644 --- a/src/core/utils/getTestContext.js +++ b/src/core/utils/getTestContext.js @@ -1,8 +1,5 @@ - - let context = null; - /** * returns a little webGL context to use for program inspection. * @@ -13,7 +10,7 @@ export default function getTestContext() { - if(!context) + if (!context) { const canvas = document.createElement('canvas'); const options = {}; @@ -21,10 +18,9 @@ canvas.width = 1; canvas.height = 1; - - context = canvas.getContext('webgl2', options) || - canvas.getContext('webgl', options) || - canvas.getContext('experimental-webgl', options); + context = canvas.getContext('webgl2', options) + || canvas.getContext('webgl', options) + || canvas.getContext('experimental-webgl', options); if (!context) { diff --git a/src/extras/webgl/TilingSpriteRenderer.js b/src/extras/webgl/TilingSpriteRenderer.js index eee3b5c..3743b62 100644 --- a/src/extras/webgl/TilingSpriteRenderer.js +++ b/src/extras/webgl/TilingSpriteRenderer.js @@ -1,6 +1,5 @@ import * as core from '../../core'; import { WRAP_MODES } from '../../core/const'; -import { GLShader } from 'pixi-gl-core'; import { readFileSync } from 'fs'; import { join } from 'path'; @@ -26,7 +25,7 @@ { super(renderer); - const uniforms = {globals:this.renderer.globalUniforms}; + const uniforms = { globals: this.renderer.globalUniforms }; this.shader = new core.Shader.from( readFileSync(join(__dirname, './tilingSprite.vert'), 'utf8'), @@ -69,8 +68,6 @@ vertices[5] = vertices[7] = 1.0 - ts.anchor.y; } - // quad.upload(); - const tex = ts._texture; const baseTex = tex.baseTexture; const lt = ts.tileTransform.localTransform; @@ -96,7 +93,6 @@ const shader = isSimple ? this.simpleShader : this.shader; - const w = tex.width; const h = tex.height; const W = ts._width; @@ -135,7 +131,7 @@ color[3] = ts.worldAlpha; shader.uniforms.uColor = color; shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - shader.uniforms.uSampler = tex;//renderer.texture.bind(tex.baseTexture, 0); + shader.uniforms.uSampler = tex; renderer.shader.bind(shader); renderer.geometry.bind(quad, renderer.shader.getGLShader()); diff --git a/src/mesh/webgl/MeshRenderer.js b/src/mesh/webgl/MeshRenderer.js index 1089c3c..2b78908 100644 --- a/src/mesh/webgl/MeshRenderer.js +++ b/src/mesh/webgl/MeshRenderer.js @@ -1,9 +1,5 @@ import * as core from '../../core'; -const byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; - -const matrixIdentity = core.Matrix.IDENTITY; - /** * WebGL renderer plugin for tiling sprites * @@ -67,16 +63,6 @@ // then render it this.renderer.geometry.draw(mesh.drawMode, mesh.size, mesh.start, mesh.geometry.instanceCount); } - - - /** - * draws mesh - * @param {PIXI.mesh.RawMesh} mesh mesh instance - */ - draw(mesh) - { - mesh.geometry.glVertexArrayObjects[this.CONTEXT_UID].draw(mesh.drawMode, mesh.size, mesh.start, mesh.geometry.instanceCount); - } } core.WebGLRenderer.registerPlugin('mesh', MeshRenderer); diff --git a/src/particles/webgl/ParticleBuffer.js b/src/particles/webgl/ParticleBuffer.js index 58b2642..24a6f9b 100644 --- a/src/particles/webgl/ParticleBuffer.js +++ b/src/particles/webgl/ParticleBuffer.js @@ -1,5 +1,5 @@ import GLBuffer from '../../core/renderers/webgl/systems/geometry/GLBuffer'; -import VertexArrayObject from '../../core/renderers/webgl/systems/geometry/VertexArrayObject'; +// import VertexArrayObject from '../../core/renderers/webgl/systems/geometry/VertexArrayObject'; import createIndicesForQuads from '../../core/utils/createIndicesForQuads'; @@ -157,8 +157,8 @@ this.staticData = new Float32Array(this.size * this.staticStride * 4); this.staticBuffer = GLBuffer.createVertexBuffer(gl, this.staticData, gl.STATIC_DRAW); - this.vao = new VertexArrayObject(gl) - .addIndex(this.indexBuffer); + // this.vao = new VertexArrayObject(gl) + // .addIndex(this.indexBuffer); for (let i = 0; i < this.dynamicProperties.length; ++i) {