/*
* Filter
* Visit http://createjs.com/ for documentation, updates and examples.
*
* Copyright (c) 2010 gskinner.com, inc.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @module EaselJS
*/
// namespace:
this.createjs = this.createjs||{};
(function() {
"use strict";
/**
* Base class that all filters should inherit from. Filters need to be applied to objects that have been cached using
* the {{#crossLink "DisplayObject/cache"}}{{/crossLink}} method. If an object changes, please cache it again, or use
* {{#crossLink "DisplayObject/updateCache"}}{{/crossLink}}. Note that the filters must be applied before caching.
*
* <h4>Example</h4>
* myInstance.filters = [
* new createjs.ColorFilter(0, 0, 0, 1, 255, 0, 0),
* new createjs.BlurFilter(5, 5, 10)
* ];
* myInstance.cache(0,0, 100, 100);
*
* Note that each filter can implement a {{#crossLink "Filter/getBounds"}}{{/crossLink}} method, which returns the
* margins that need to be applied in order to fully display the filter. For example, the {{#crossLink "BlurFilter"}}{{/crossLink}}
* will cause an object to feather outwards, resulting in a margin around the shape.
*
* <h4>EaselJS Filters</h4>
* EaselJS comes with a number of pre-built filters. Note that individual filters are not compiled into the minified
* version of EaselJS. To use them, you must include them manually in the HTML.
* <ul><li>{{#crossLink "AlphaMapFilter"}}{{/crossLink}} : Map a greyscale image to the alpha channel of a display object</li>
* <li>{{#crossLink "AlphaMaskFilter"}}{{/crossLink}}: Map an image's alpha channel to the alpha channel of a display object</li>
* <li>{{#crossLink "BlurFilter"}}{{/crossLink}}: Apply vertical and horizontal blur to a display object</li>
* <li>{{#crossLink "ColorFilter"}}{{/crossLink}}: Color transform a display object</li>
* <li>{{#crossLink "ColorMatrixFilter"}}{{/crossLink}}: Transform an image using a {{#crossLink "ColorMatrix"}}{{/crossLink}}</li>
* </ul>
*
* @class Filter
* @constructor
**/
var Filter = function() {
this.initialize();
};
var p = Filter.prototype;
// public properties:
p.useGL = false;
// protected properties:
p._workContext = undefined;
// constructor:
/**
* Initialization method.
* @method initialize
* @protected
**/
p.initialize = function() { };
// public methods:
/**
* Returns a rectangle with values indicating the margins required to draw the filter or null.
* For example, a filter that will extend the drawing area 4 pixels to the left, and 7 pixels to the right
* (but no pixels up or down) would return a rectangle with (x=-4, y=0, width=11, height=0).
* @method getBounds
* @return {Rectangle} a rectangle object indicating the margins required to draw the filter or null if the filter does not effect bounds.
**/
p.getBounds = function() {
return null;
};
/**
* Applies the filter to the specified context. Filter only works with WebGL - use subclass applyFilter for individual filters.
* @method applyFilter
* @param {CanvasRenderingContext2D} ctx The 2D context to use as the source.
* @param {Number} x The x position to use for the source rect.
* @param {Number} y The y position to use for the source rect.
* @param {Number} width The width to use for the source rect.
* @param {Number} height The height to use for the source rect.
* @param {CanvasRenderingContext2D} [targetCtx] The 2D context to draw the result to. Defaults to the context passed to ctx.
* @param {Number} [targetX] The x position to draw the result to. Defaults to the value passed to x.
* @param {Number} [targetY] The y position to draw the result to. Defaults to the value passed to y.
* @return {Boolean} If the filter was applied successfully.
**/
p.applyFilter = function(ctx, x, y, width, height, targetCtx, targetX, targetY) { }
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
**/
p.toString = function() {
return "[Filter]";
};
/**
* Returns a clone of this Filter instance.
* @method clone
* @return {Filter} A clone of the current Filter instance.
**/
p.clone = function() {
return new Filter();
};
/**
* Attempt to creates a WebGLContextRenderer for fast, efficient filter rendering. Used during filter initialization.
* If it cannot be done, or this.useGL is set to false, then the filter is rendered normally using a Context2D.
* @method _createWebGLRenderer
* @protected
**/
p._createWebGLRenderer = function() {
var cvs = document.createElement("canvas");
var ctx = this._workContext = cvs.getContext("experimental-webgl", {preserveDrawingBuffer: true, antialias:1, alpha:1, stencil:1}) ||
cvs.getContext("webgl", {preserveDrawingBuffer: true, antialias:1, alpha:1, stencil:1}) ||
cvs.getContext("moz-webgl", {preserveDrawingBuffer: true, antialias:1, alpha:1, stencil:1});
if(!ctx) { return; }
if(!this._initShaders(ctx)) {
// Shaders can't be initialized. Be silent about it.
console.log("Cannot initialize work context shaders or buffers. Reverting to 2D method.");
this._workContext = null;
} else {
this._initBuffers(ctx);
this._initUniforms(ctx, ctx.program);
}
}
/**
* Setup the shaders for WebGL rendering. Each filter is responsible for its own fragment shader.
* @method _initShaders
* @param ctx WebGL Context.
* @protected
**/
p._initShaders = function(ctx) {
// Create vertex shader.
var vertexShader = ctx.createShader(ctx.VERTEX_SHADER);
ctx.shaderSource(vertexShader, this._getVertexShader());
ctx.compileShader(vertexShader);
// Show any shader compilation errors.
if(!ctx.getShaderParameter(vertexShader, ctx.COMPILE_STATUS)) { console.log(ctx.getShaderInfoLog(vertexShader)); }
// Create fragment shader
var textureShader = ctx.createShader(ctx.FRAGMENT_SHADER);
ctx.shaderSource(textureShader, this._getFragmentShader());
ctx.compileShader(textureShader);
// Show any shader compilation errors.
if(!ctx.getShaderParameter(textureShader, ctx.COMPILE_STATUS)) { console.log(ctx.getShaderInfoLog(textureShader)); }
// Create shader program
var program = ctx.program = ctx.createProgram();
// Attach the shaders to the program and link it to the context.
ctx.attachShader(program, vertexShader);
ctx.attachShader(program, textureShader);
ctx.linkProgram(program);
if(!ctx.getProgramParameter(program, ctx.LINK_STATUS)) {
console.log("Cannot link shader.");
return false;
}
// Context now knows to use the shader program.
ctx.useProgram(program);
// Link attributes to references and enable them for use by the buffer.
ctx.enableVertexAttribArray(ctx.vertexPositionAttribute = ctx.getAttribLocation(program, "aVertexPosition"));
// Set uniform references.
ctx.persMatrixUniform = ctx.getUniformLocation(program, "uPMatrix");
// Set the samplerIDs within the shader.
ctx.activeTexture(ctx.TEXTURE0);
ctx.uniform1i(ctx.getUniformLocation(program, "uSampler"), 0);
// Setup blending. This allows the use of alpha.
ctx.blendFuncSeparate(ctx.SRC_ALPHA, ctx.ONE_MINUS_SRC_ALPHA, ctx.SRC_ALPHA, ctx.ONE);
ctx.enable(ctx.BLEND);
// Disable depth test. Objects will be drawn in order of hierarchy, and the z position is not used.
ctx.disable(ctx.DEPTH_TEST);
return true;
}
/**
* Setup the buffers and camera for the object. In this case, just create a rectangle that occupies the full stage.
* @method _initBuffers
* @param ctx WebGL Context.
* @protected
**/
p._initBuffers = function(ctx) {
// Setup buffers
ctx.bindBuffer(ctx.ARRAY_BUFFER, ctx.createBuffer());
// Connect the buffers to the shader so it knows what the data it's receiving is.
ctx.vertexAttribPointer(ctx.vertexPositionAttribute, 3, ctx.FLOAT, 0, 12, 0);
// Write vertex positions to buffer.
ctx.bufferData(ctx.ARRAY_BUFFER, new Float32Array([
0,1,0,
0,0,0,
1,1,0,
1,0,0
]), ctx.STATIC_DRAW);
// Set the camera.
ctx.uniformMatrix4fv(ctx.persMatrixUniform, false, new Float32Array([
2, 0, 0, 0,
0,-2, 0, 0,
0, 0, 0, 0,
-1, 1, 0, 1
]));
ctx.colorMask(true, true, true, true);
ctx.clearColor(0,0,0,0);
return true;
}
/**
* Setup the uniforms for the fragment shader.
* Each filter is responsible for its own fragment shader uniforms, as they are responsible for their own fragment shaders.
* @method _initUniforms
* @param ctx WebGL Context.
* @protected
**/
p._initUniforms = function(ctx, program) { }
/**
* Setup the viewport. May change with canvas size.
* @method _initUniforms
* @param ctx WebGL Context.
* @protected
**/
p._initViewport = function(ctx, width, height) {
var canvas = ctx.canvas;
canvas.width = width;
canvas.height = height;
// Setup camera viewport.
ctx.viewport(0, 0, width, height);
ctx.clear(ctx.COLOR_BUFFER_BIT | ctx.DEPTH_BUFFER_BIT | ctx.STENCIL_BUFFER_BIT);
}
/**
* Pass in textures. May change with updated cache.
* @method _initUniforms
* @param ctx WebGL Context.
* @protected
**/
p._initTexture = function(ctx, src, mask){
var texture = ctx.createTexture();
texture.image = src;
// Sets the context to point to a texture storage index in memory to bind the texture to.
mask ? ctx.activeTexture(ctx.TEXTURE1) : ctx.activeTexture(ctx.TEXTURE0);
// This physically adds the texture object to the context for the shader to access. However, it must still be "drawn".
ctx.bindTexture(ctx.TEXTURE_2D, texture);
// Image is flipped in the shader.
ctx.pixelStorei(ctx.UNPACK_FLIP_Y_WEBGL, true);
// This "draws" the texture out so the context knows how to read it.
try {
ctx.texImage2D(ctx.TEXTURE_2D, 0, ctx.RGBA, ctx.RGBA, ctx.UNSIGNED_BYTE, src);
} catch(e) {
ctx.texSubImage2D(ctx.TEXTURE_2D, 0, 0, 0, src.width, src.height, ctx.RGBA, ctx.UNSIGNED_SHORT, src);
}
// Setup a few parameters for the texture. Namely, pointing out its bounds and edge behaviours.
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, ctx.LINEAR);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, ctx.LINEAR);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, ctx.CLAMP_TO_EDGE);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, ctx.CLAMP_TO_EDGE);
}
/**
* @method _getVertexShader
* Get vertex shader in GLSL code. This sets the positions of each point on the context in 3D space.
* @returns {String}
* @protected
*/
p._getVertexShader = function() {
return "" +
"attribute vec3 aVertexPosition; \n" +
"uniform mat4 uPMatrix; \n" +
"varying vec2 vTextureCoord; \n" +
"void main(void) { \n" +
" vTextureCoord = vec2(aVertexPosition.x, aVertexPosition.y); \n" +
" gl_Position = uPMatrix * vec4(aVertexPosition, 1.0); \n" +
"}";
};
/**
* @method _getFragmentShader
* Get fragment shader code in GLSL.
* Filters are responsible for their own fragment shaders.
* @returns {String}
* @protected
*/
p._getFragmentShader = function() {
return "" +
"precision mediump float; \n" +
"varying vec2 vTextureCoord; \n" +
"uniform sampler2D uSampler; \n" +
// Main
"void main(void) { \n" +
" gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t)); \n" +
"}";
};
createjs.Filter = Filter;
}());