code
stringlengths
10
343k
docstring
stringlengths
36
21.9k
func_name
stringlengths
1
3.35k
language
stringclasses
1 value
repo
stringlengths
7
58
path
stringlengths
4
131
url
stringlengths
44
195
license
stringclasses
5 values
TextureManager.prototype.register = function register(input, slot) { var _this = this; var source = input.data; var textureId = input.id; var options = input.options || {}; var texture = this.registry[textureId]; var spec; if (!texture) { texture = new Texture(this.gl, options); texture.setImage(this._checkerboard); // Add texture to registry spec = this.registry[textureId] = { resampleRate: options.resampleRate || null, lastResample: null, isLoaded: false, texture: texture, source: source, id: textureId, slot: slot }; // Handle array if (Array.isArray(source) || source instanceof Uint8Array || source instanceof Float32Array) { this.bindTexture(textureId); texture.setArray(source); spec.isLoaded = true; } // Handle video else if (source instanceof HTMLVideoElement) { source.addEventListener('loadeddata', function() { _this.bindTexture(textureId); texture.setImage(source); spec.isLoaded = true; spec.source = source; }); } // Handle image url else if (typeof source === 'string') { loadImage(source, function (img) { _this.bindTexture(textureId); texture.setImage(img); spec.isLoaded = true; spec.source = img; }); } } return textureId; };
Creates a spec and creates a texture based on given texture data. Handles loading assets if necessary. @method @param {Object} input Object containing texture id, texture data and options used to draw texture. @param {Number} slot Texture slot to bind generated texture to. @return {undefined} undefined
register ( input , slot )
javascript
Famous/engine
webgl-renderers/TextureManager.js
https://github.com/Famous/engine/blob/master/webgl-renderers/TextureManager.js
MIT
TextureManager.prototype.bindTexture = function bindTexture(id) { var spec = this.registry[id]; if (this._activeTexture !== spec.slot) { this.gl.activeTexture(this.gl.TEXTURE0 + spec.slot); this._activeTexture = spec.slot; } if (this._boundTexture !== id) { this._boundTexture = id; spec.texture.bind(); } if (this._needsResample[spec.id]) { // TODO: Account for resampling of arrays. spec.texture.setImage(spec.source); this._needsResample[spec.id] = false; } };
Sets active texture slot and binds target texture. Also handles resampling when necessary. @method @param {Number} id Identifier used to retreive texture spec @return {undefined} undefined
bindTexture ( id )
javascript
Famous/engine
webgl-renderers/TextureManager.js
https://github.com/Famous/engine/blob/master/webgl-renderers/TextureManager.js
MIT
function loadImage (input, callback) { var image = (typeof input === 'string' ? new Image() : input) || {}; image.crossOrigin = 'anonymous'; if (!image.src) image.src = input; if (!image.complete) { image.onload = function () { callback(image); }; } else { callback(image); } return image; } /** * Sets active texture slot and binds target texture. Also handles * resampling when necessary. * * @method * * @param {Number} id Identifier used to retreive texture spec * * @return {undefined} undefined */ TextureManager.prototype.bindTexture = function bindTexture(id) { var spec = this.registry[id]; if (this._activeTexture !== spec.slot) { this.gl.activeTexture(this.gl.TEXTURE0 + spec.slot); this._activeTexture = spec.slot; } if (this._boundTexture !== id) { this._boundTexture = id; spec.texture.bind(); } if (this._needsResample[spec.id]) { // TODO: Account for resampling of arrays. spec.texture.setImage(spec.source); this._needsResample[spec.id] = false; } }; module.exports = TextureManager;
Loads an image from a string or Image object and executes a callback function. @method @private @param {Object|String} input The input image data to load as an asset. @param {Function} callback The callback function to be fired when the image has finished loading. @return {Object} Image object being loaded.
loadImage ( input , callback )
javascript
Famous/engine
webgl-renderers/TextureManager.js
https://github.com/Famous/engine/blob/master/webgl-renderers/TextureManager.js
MIT
function Buffer(target, type, gl) { this.buffer = null; this.target = target; this.type = type; this.data = []; this.gl = gl; }
Buffer is a private class that wraps the vertex data that defines the the points of the triangles that webgl draws. Each buffer maps to one attribute of a mesh. @class Buffer @constructor @param {Number} target The bind target of the buffer to update: ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER @param {Object} type Array type to be used in calls to gl.bufferData. @param {WebGLContext} gl The WebGL context that the buffer is hosted by. @return {undefined} undefined
Buffer ( target , type , gl )
javascript
Famous/engine
webgl-renderers/Buffer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Buffer.js
MIT
Buffer.prototype.subData = function subData() { var gl = this.gl; var data = []; // to prevent against maximum call-stack issue. for (var i = 0, chunk = 10000; i < this.data.length; i += chunk) data = Array.prototype.concat.apply(data, this.data.slice(i, i + chunk)); this.buffer = this.buffer || gl.createBuffer(); gl.bindBuffer(this.target, this.buffer); gl.bufferData(this.target, new this.type(data), gl.STATIC_DRAW); };
Creates a WebGL buffer if one does not yet exist and binds the buffer to to the context. Runs bufferData with appropriate data. @method @return {undefined} undefined
subData ( )
javascript
Famous/engine
webgl-renderers/Buffer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Buffer.js
MIT
function createCheckerBoard() { var context = document.createElement('canvas').getContext('2d'); context.canvas.width = context.canvas.height = 128; for (var y = 0; y < context.canvas.height; y += 16) { for (var x = 0; x < context.canvas.width; x += 16) { context.fillStyle = (x ^ y) & 16 ? '#FFF' : '#DDD'; context.fillRect(x, y, 16, 16); } } return context.canvas; }
Generates a checkerboard pattern to be used as a placeholder texture while an image loads over the network. @method createCheckerBoard @return {HTMLCanvasElement} The `canvas` element that has been used in order to generate the pattern.
createCheckerBoard ( )
javascript
Famous/engine
webgl-renderers/createCheckerboard.js
https://github.com/Famous/engine/blob/master/webgl-renderers/createCheckerboard.js
MIT
function BufferRegistry(context) { this.gl = context; this.registry = {}; this._dynamicBuffers = []; this._staticBuffers = []; this._arrayBufferMax = 30000; this._elementBufferMax = 30000; }
BufferRegistry is a class that manages allocation of buffers to input geometries. @class BufferRegistry @constructor @param {WebGLContext} context WebGL drawing context to be passed to buffers. @return {undefined} undefined
BufferRegistry ( context )
javascript
Famous/engine
webgl-renderers/BufferRegistry.js
https://github.com/Famous/engine/blob/master/webgl-renderers/BufferRegistry.js
MIT
BufferRegistry.prototype.allocate = function allocate(geometryId, name, value, spacing, dynamic) { var vertexBuffers = this.registry[geometryId] || (this.registry[geometryId] = { keys: [], values: [], spacing: [], offset: [], length: [] }); var j = vertexBuffers.keys.indexOf(name); var isIndex = name === INDICES; var bufferFound = false; var newOffset; var offset = 0; var length; var buffer; var k; if (j === -1) { j = vertexBuffers.keys.length; length = isIndex ? value.length : Math.floor(value.length / spacing); if (!dynamic) { // Use a previously created buffer if available. for (k = 0; k < this._staticBuffers.length; k++) { if (isIndex === this._staticBuffers[k].isIndex) { newOffset = this._staticBuffers[k].offset + value.length; if ((!isIndex && newOffset < this._arrayBufferMax) || (isIndex && newOffset < this._elementBufferMax)) { buffer = this._staticBuffers[k].buffer; offset = this._staticBuffers[k].offset; this._staticBuffers[k].offset += value.length; bufferFound = true; break; } } } // Create a new static buffer in none were found. if (!bufferFound) { buffer = new Buffer( isIndex ? this.gl.ELEMENT_ARRAY_BUFFER : this.gl.ARRAY_BUFFER, isIndex ? Uint16Array : Float32Array, this.gl ); this._staticBuffers.push({ buffer: buffer, offset: value.length, isIndex: isIndex }); } } else { // For dynamic geometries, always create new buffer. buffer = new Buffer( isIndex ? this.gl.ELEMENT_ARRAY_BUFFER : this.gl.ARRAY_BUFFER, isIndex ? Uint16Array : Float32Array, this.gl ); this._dynamicBuffers.push({ buffer: buffer, offset: value.length, isIndex: isIndex }); } // Update the registry for the spec with buffer information. vertexBuffers.keys.push(name); vertexBuffers.values.push(buffer); vertexBuffers.spacing.push(spacing); vertexBuffers.offset.push(offset); vertexBuffers.length.push(length); } var len = value.length; for (k = 0; k < len; k++) { vertexBuffers.values[j].data[offset + k] = value[k]; } vertexBuffers.values[j].subData(); }; module.exports = BufferRegistry;
Binds and fills all the vertex data into webgl buffers. Will reuse buffers if possible. Populates registry with the name of the buffer, the WebGL buffer object, spacing of the attribute, the attribute's offset within the buffer, and finally the length of the buffer. This information is later accessed by the root to draw the buffers. @method @param {Number} geometryId Id of the geometry instance that holds the buffers. @param {String} name Key of the input buffer in the geometry. @param {Array} value Flat array containing input data for buffer. @param {Number} spacing The spacing, or itemSize, of the input buffer. @param {Boolean} dynamic Boolean denoting whether a geometry is dynamic or static. @return {undefined} undefined
allocate ( geometryId , name , value , spacing , dynamic )
javascript
Famous/engine
webgl-renderers/BufferRegistry.js
https://github.com/Famous/engine/blob/master/webgl-renderers/BufferRegistry.js
MIT
function WebGLRenderer(canvas, compositor) { canvas.classList.add('famous-webgl-renderer'); this.canvas = canvas; this.compositor = compositor; var gl = this.gl = this.getWebGLContext(this.canvas); gl.clearColor(0.0, 0.0, 0.0, 0.0); gl.polygonOffset(0.1, 0.1); gl.enable(gl.POLYGON_OFFSET_FILL); gl.enable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl.depthFunc(gl.LEQUAL); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); this.meshRegistry = new Registry(); this.cutoutRegistry = new Registry(); this.lightRegistry = new Registry(); this.numLights = 0; this.ambientLightColor = [0, 0, 0]; this.lightPositions = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; this.lightColors = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; this.textureManager = new TextureManager(gl); this.bufferRegistry = new BufferRegistry(gl); this.program = new Program(gl, { debug: true }); this.state = { boundArrayBuffer: null, boundElementBuffer: null, lastDrawn: null, enabledAttributes: {}, enabledAttributesKeys: [] }; this.resolutionName = ['u_resolution']; this.resolutionValues = [[0, 0, 0]]; this.cachedSize = []; /* The projectionTransform has some constant components, i.e. the z scale, and the x and y translation. The z scale keeps the final z position of any vertex within the clip's domain by scaling it by an arbitrarily small coefficient. This has the advantage of being a useful default in the event of the user forgoing a near and far plane, an alien convention in dom space as in DOM overlapping is conducted via painter's algorithm. The x and y translation transforms the world space origin to the top left corner of the screen. The final component (this.projectionTransform[15]) is initialized as 1 because certain projection models, e.g. the WC3 specified model, keep the XY plane as the projection hyperplane. */ this.projectionTransform = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -0.000001, 0, -1, 1, 0, 1]; // TODO: remove this hack var cutout = this.cutoutGeometry = { spec: { id: -1, bufferValues: [[-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]], bufferNames: ['a_pos'], type: 'TRIANGLE_STRIP' } }; this.bufferRegistry.allocate( this.cutoutGeometry.spec.id, cutout.spec.bufferNames[0], cutout.spec.bufferValues[0], 3 ); }
WebGLRenderer is a private class that manages all interactions with the WebGL API. Each frame it receives commands from the compositor and updates its registries accordingly. Subsequently, the draw function is called and the WebGLRenderer issues draw calls for all meshes in its registry. @class WebGLRenderer @constructor @param {Element} canvas The DOM element that GL will paint itself onto. @param {Compositor} compositor Compositor used for querying the time from. @return {undefined} undefined
WebGLRenderer ( canvas , compositor )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.getWebGLContext = function getWebGLContext(canvas) { var names = ['webgl', 'experimental-webgl', 'webkit-3d', 'moz-webgl']; var context; for (var i = 0, len = names.length; i < len; i++) { try { context = canvas.getContext(names[i]); } catch (error) { console.error('Error creating WebGL context: ' + error.toString()); } if (context) return context; } if (!context) { console.error('Could not retrieve WebGL context. Please refer to https://www.khronos.org/webgl/ for requirements'); return false; } };
Attempts to retreive the WebGLRenderer context using several accessors. For browser compatability. Throws on error. @method @param {Object} canvas Canvas element from which the context is retreived @return {Object} WebGLContext WebGL context
getWebGLContext ( canvas )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.createLight = function createLight(path) { this.numLights++; var light = { color: [0, 0, 0], position: [0, 0, 0] }; this.lightRegistry.register(path, light); return light; };
Adds a new base spec to the light registry at a given path. @method @param {String} path Path used as id of new light in lightRegistry @return {Object} Newly created light spec
createLight ( path )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.createMesh = function createMesh(path) { var uniforms = keyValueToArrays({ u_opacity: 1, u_transform: identity, u_size: [0, 0, 0], u_baseColor: [0.5, 0.5, 0.5, 1], u_positionOffset: [0, 0, 0], u_normals: [0, 0, 0], u_flatShading: 0, u_glossiness: [0, 0, 0, 0] }); var mesh = { depth: null, uniformKeys: uniforms.keys, uniformValues: uniforms.values, buffers: {}, geometry: null, drawType: null, textures: [], visible: true }; this.meshRegistry.register(path, mesh); return mesh; };
Adds a new base spec to the mesh registry at a given path. @method @param {String} path Path used as id of new mesh in meshRegistry. @return {Object} Newly created mesh spec.
createMesh ( path )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setCutoutState = function setCutoutState(path, usesCutout) { var cutout = this.getOrSetCutout(path); cutout.visible = usesCutout; };
Sets flag on indicating whether to do skip draw phase for cutout mesh at given path. @method @param {String} path Path used as id of target cutout mesh. @param {Boolean} usesCutout Indicates the presence of a cutout mesh @return {undefined} undefined
setCutoutState ( path , usesCutout )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setMeshVisibility = function setMeshVisibility(path, visibility) { var mesh = this.meshRegistry.get(path) || this.createMesh(path); mesh.visible = visibility; };
Sets flag on indicating whether to do skip draw phase for mesh at given path. @method @param {String} path Path used as id of target mesh. @param {Boolean} visibility Indicates the visibility of target mesh. @return {undefined} undefined
setMeshVisibility ( path , visibility )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.removeMesh = function removeMesh(path) { this.meshRegistry.unregister(path); };
Deletes a mesh from the meshRegistry. @method @param {String} path Path used as id of target mesh. @return {undefined} undefined
removeMesh ( path )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setCutoutUniform = function setCutoutUniform(path, uniformName, uniformValue) { var cutout = this.getOrSetCutout(path); var index = cutout.uniformKeys.indexOf(uniformName); if (uniformValue.length) { for (var i = 0, len = uniformValue.length; i < len; i++) { cutout.uniformValues[index][i] = uniformValue[i]; } } else { cutout.uniformValues[index] = uniformValue; } };
Creates or retreives cutout @method @param {String} path Path used as id of cutout in cutout registry. @param {String} uniformName Identifier used to upload value @param {Array} uniformValue Value of uniform data @return {undefined} undefined
setCutoutUniform ( path , uniformName , uniformValue )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setMeshOptions = function(path, options) { var mesh = this.meshRegistry.get(path) || this.createMesh(path); mesh.options = options; return this; };
Edits the options field on a mesh @method @param {String} path Path used as id of target mesh @param {Object} options Map of draw options for mesh @return {WebGLRenderer} this
WebGLRenderer.prototype.setMeshOptions ( path , options )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setAmbientLightColor = function setAmbientLightColor(path, r, g, b) { this.ambientLightColor[0] = r; this.ambientLightColor[1] = g; this.ambientLightColor[2] = b; return this; };
Changes the color of the fixed intensity lighting in the scene @method @param {String} path Path used as id of light @param {Number} r red channel @param {Number} g green channel @param {Number} b blue channel @return {WebGLRenderer} this
setAmbientLightColor ( path , r , g , b )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setLightPosition = function setLightPosition(path, x, y, z) { var light = this.lightRegistry.get(path) || this.createLight(path); light.position[0] = x; light.position[1] = y; light.position[2] = z; return this; };
Changes the location of the light in the scene @method @param {String} path Path used as id of light @param {Number} x x position @param {Number} y y position @param {Number} z z position @return {WebGLRenderer} this
setLightPosition ( path , x , y , z )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setLightColor = function setLightColor(path, r, g, b) { var light = this.lightRegistry.get(path) || this.createLight(path); light.color[0] = r; light.color[1] = g; light.color[2] = b; return this; };
Changes the color of a dynamic intensity lighting in the scene @method @param {String} path Path used as id of light in light Registry. @param {Number} r red channel @param {Number} g green channel @param {Number} b blue channel @return {WebGLRenderer} this
setLightColor ( path , r , g , b )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.handleMaterialInput = function handleMaterialInput(path, name, material) { var mesh = this.meshRegistry.get(path) || this.createMesh(path); material = compileMaterial(material, mesh.textures.length); // Set uniforms to enable texture! mesh.uniformValues[mesh.uniformKeys.indexOf(name)][0] = -material._id; // Register textures! var i = material.textures.length; while (i--) { mesh.textures.push( this.textureManager.register(material.textures[i], mesh.textures.length + i) ); } // Register material! this.program.registerMaterial(name, material); return this.updateSize(); };
Compiles material spec into program shader @method @param {String} path Path used as id of cutout in cutout registry. @param {String} name Name that the rendering input the material is bound to @param {Object} material Material spec @return {WebGLRenderer} this
handleMaterialInput ( path , name , material )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setGeometry = function setGeometry(path, geometry, drawType, dynamic) { var mesh = this.meshRegistry.get(path) || this.createMesh(path); mesh.geometry = geometry; mesh.drawType = drawType; mesh.dynamic = dynamic; return this; };
Changes the geometry data of a mesh @method @param {String} path Path used as id of cutout in cutout registry. @param {Object} geometry Geometry object containing vertex data to be drawn @param {Number} drawType Primitive identifier @param {Boolean} dynamic Whether geometry is dynamic @return {undefined} undefined
setGeometry ( path , geometry , drawType , dynamic )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setMeshUniform = function setMeshUniform(path, uniformName, uniformValue) { var mesh = this.meshRegistry.get(path) || this.createMesh(path); var index = mesh.uniformKeys.indexOf(uniformName); if (index === -1) { mesh.uniformKeys.push(uniformName); mesh.uniformValues.push(uniformValue); } else { mesh.uniformValues[index] = uniformValue; } };
Uploads a new value for the uniform data when the mesh is being drawn @method @param {String} path Path used as id of mesh in mesh registry @param {String} uniformName Identifier used to upload value @param {Array} uniformValue Value of uniform data @return {undefined} undefined
setMeshUniform ( path , uniformName , uniformValue )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.bufferData = function bufferData(geometryId, bufferName, bufferValue, bufferSpacing, isDynamic) { this.bufferRegistry.allocate(geometryId, bufferName, bufferValue, bufferSpacing, isDynamic); };
Allocates a new buffer using the internal BufferRegistry. @method @param {Number} geometryId Id of geometry in geometry registry @param {String} bufferName Attribute location name @param {Array} bufferValue Vertex data @param {Number} bufferSpacing The dimensions of the vertex @param {Boolean} isDynamic Whether geometry is dynamic @return {undefined} undefined
bufferData ( geometryId , bufferName , bufferValue , bufferSpacing , isDynamic )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.draw = function draw(renderState) { var time = this.compositor.getTime(); this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT); this.textureManager.update(time); this.meshRegistryKeys = sorter(this.meshRegistry.getKeys(), this.meshRegistry.getKeyToValue()); this.setGlobalUniforms(renderState); this.drawCutouts(); this.drawMeshes(); };
Triggers the 'draw' phase of the WebGLRenderer. Iterates through registries to set uniforms, set attributes and issue draw commands for renderables. @method @param {Object} renderState Parameters provided by the compositor, that affect the rendering of all renderables. @return {undefined} undefined
draw ( renderState )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.drawMeshes = function drawMeshes() { var gl = this.gl; var buffers; var mesh; var meshes = this.meshRegistry.getValues(); for(var i = 0; i < meshes.length; i++) { mesh = meshes[i]; if (!mesh) continue; buffers = this.bufferRegistry.registry[mesh.geometry]; if (!mesh.visible) continue; if (mesh.uniformValues[0] < 1) { gl.depthMask(false); gl.enable(gl.BLEND); } else { gl.depthMask(true); gl.disable(gl.BLEND); } if (!buffers) continue; var j = mesh.textures.length; while (j--) this.textureManager.bindTexture(mesh.textures[j]); if (mesh.options) this.handleOptions(mesh.options, mesh); this.program.setUniforms(mesh.uniformKeys, mesh.uniformValues); this.drawBuffers(buffers, mesh.drawType, mesh.geometry); if (mesh.options) this.resetOptions(mesh.options); } };
Iterates through and draws all registered meshes. This includes binding textures, handling draw options, setting mesh uniforms and drawing mesh buffers. @method @return {undefined} undefined
drawMeshes ( )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.drawCutouts = function drawCutouts() { var cutout; var buffers; var cutouts = this.cutoutRegistry.getValues(); var len = cutouts.length; this.gl.disable(this.gl.CULL_FACE); this.gl.enable(this.gl.BLEND); this.gl.depthMask(true); for (var i = 0; i < len; i++) { cutout = cutouts[i]; if (!cutout) continue; buffers = this.bufferRegistry.registry[cutout.geometry]; if (!cutout.visible) continue; this.program.setUniforms(cutout.uniformKeys, cutout.uniformValues); this.drawBuffers(buffers, cutout.drawType, cutout.geometry); } this.gl.enable(this.gl.CULL_FACE); };
Iterates through and draws all registered cutout meshes. Blending is disabled, cutout uniforms are set and finally buffers are drawn. @method @return {undefined} undefined
drawCutouts ( )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.setGlobalUniforms = function setGlobalUniforms(renderState) { var light; var stride; var lights = this.lightRegistry.getValues(); var len = lights.length; for (var i = 0; i < len; i++) { light = lights[i]; if (!light) continue; stride = i * 4; // Build the light positions' 4x4 matrix this.lightPositions[0 + stride] = light.position[0]; this.lightPositions[1 + stride] = light.position[1]; this.lightPositions[2 + stride] = light.position[2]; // Build the light colors' 4x4 matrix this.lightColors[0 + stride] = light.color[0]; this.lightColors[1 + stride] = light.color[1]; this.lightColors[2 + stride] = light.color[2]; } globalUniforms.values[0] = this.numLights; globalUniforms.values[1] = this.ambientLightColor; globalUniforms.values[2] = this.lightPositions; globalUniforms.values[3] = this.lightColors; /* * Set time and projection uniforms * projecting world space into a 2d plane representation of the canvas. * The x and y scale (this.projectionTransform[0] and this.projectionTransform[5] respectively) * convert the projected geometry back into clipspace. * The perpective divide (this.projectionTransform[11]), adds the z value of the point * multiplied by the perspective divide to the w value of the point. In the process * of converting from homogenous coordinates to NDC (normalized device coordinates) * the x and y values of the point are divided by w, which implements perspective. */ this.projectionTransform[0] = 1 / (this.cachedSize[0] * 0.5); this.projectionTransform[5] = -1 / (this.cachedSize[1] * 0.5); this.projectionTransform[11] = renderState.perspectiveTransform[11]; globalUniforms.values[4] = this.projectionTransform; globalUniforms.values[5] = this.compositor.getTime() * 0.001; globalUniforms.values[6] = renderState.viewTransform; this.program.setUniforms(globalUniforms.keys, globalUniforms.values); };
Sets uniforms to be shared by all meshes. @method @param {Object} renderState Draw state options passed down from compositor. @return {undefined} undefined
setGlobalUniforms ( renderState )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.drawBuffers = function drawBuffers(vertexBuffers, mode, id) { var gl = this.gl; var length = 0; var attribute; var location; var spacing; var offset; var buffer; var iter; var j; var i; iter = vertexBuffers.keys.length; for (i = 0; i < iter; i++) { attribute = vertexBuffers.keys[i]; // Do not set vertexAttribPointer if index buffer. if (attribute === 'indices') { j = i; continue; } // Retreive the attribute location and make sure it is enabled. location = this.program.attributeLocations[attribute]; if (location === -1) continue; if (location === undefined) { location = gl.getAttribLocation(this.program.program, attribute); this.program.attributeLocations[attribute] = location; if (location === -1) continue; } if (!this.state.enabledAttributes[attribute]) { gl.enableVertexAttribArray(location); this.state.enabledAttributes[attribute] = true; this.state.enabledAttributesKeys.push(attribute); } // Retreive buffer information used to set attribute pointer. buffer = vertexBuffers.values[i]; spacing = vertexBuffers.spacing[i]; offset = vertexBuffers.offset[i]; length = vertexBuffers.length[i]; // Skip bindBuffer if buffer is currently bound. if (this.state.boundArrayBuffer !== buffer) { gl.bindBuffer(buffer.target, buffer.buffer); this.state.boundArrayBuffer = buffer; } if (this.state.lastDrawn !== id) { gl.vertexAttribPointer(location, spacing, gl.FLOAT, gl.FALSE, 0, 4 * offset); } } // Disable any attributes that not currently being used. var len = this.state.enabledAttributesKeys.length; for (i = 0; i < len; i++) { var key = this.state.enabledAttributesKeys[i]; if (this.state.enabledAttributes[key] && vertexBuffers.keys.indexOf(key) === -1) { gl.disableVertexAttribArray(this.program.attributeLocations[key]); this.state.enabledAttributes[key] = false; } } if (length) { // If index buffer, use drawElements. if (j !== undefined) { buffer = vertexBuffers.values[j]; offset = vertexBuffers.offset[j]; spacing = vertexBuffers.spacing[j]; length = vertexBuffers.length[j]; // Skip bindBuffer if buffer is currently bound. if (this.state.boundElementBuffer !== buffer) { gl.bindBuffer(buffer.target, buffer.buffer); this.state.boundElementBuffer = buffer; } gl.drawElements(gl[mode], length, gl.UNSIGNED_SHORT, 2 * offset); } else { gl.drawArrays(gl[mode], 0, length); } } this.state.lastDrawn = id; };
Loads the buffers and issues the draw command for a geometry. @method @param {Object} vertexBuffers All buffers used to draw the geometry. @param {Number} mode Enumerator defining what primitive to draw @param {Number} id ID of geometry being drawn. @return {undefined} undefined
drawBuffers ( vertexBuffers , mode , id )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.updateSize = function updateSize(size) { if (size) { var pixelRatio = window.devicePixelRatio || 1; var displayWidth = ~~(size[0] * pixelRatio); var displayHeight = ~~(size[1] * pixelRatio); this.canvas.width = displayWidth; this.canvas.height = displayHeight; this.gl.viewport(0, 0, displayWidth, displayHeight); this.cachedSize[0] = size[0]; this.cachedSize[1] = size[1]; this.cachedSize[2] = (size[0] > size[1]) ? size[0] : size[1]; this.resolutionValues[0] = this.cachedSize; } this.program.setUniforms(this.resolutionName, this.resolutionValues); return this; };
Updates the width and height of parent canvas, sets the viewport size on the WebGL context and updates the resolution uniform for the shader program. Size is retreived from the container object of the renderer. @method @param {Array} size width, height and depth of canvas @return {undefined} undefined
updateSize ( size )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.handleOptions = function handleOptions(options, mesh) { var gl = this.gl; if (!options) return; if (options.blending) gl.enable(gl.BLEND); switch (options.side) { case 'double': this.gl.cullFace(this.gl.FRONT); this.drawBuffers(this.bufferRegistry.registry[mesh.geometry], mesh.drawType, mesh.geometry); this.gl.cullFace(this.gl.BACK); break; case 'back': gl.cullFace(gl.FRONT); break; } };
Updates the state of the WebGL drawing context based on custom parameters defined on a mesh. @method @param {Object} options Draw state options to be set to the context. @param {Mesh} mesh Associated Mesh @return {undefined} undefined
handleOptions ( options , mesh )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
WebGLRenderer.prototype.resetOptions = function resetOptions(options) { var gl = this.gl; if (!options) return; if (options.blending) gl.disable(gl.BLEND); if (options.side === 'back') gl.cullFace(gl.BACK); };
Resets the state of the WebGL drawing context to default values. @method @param {Object} options Draw state options to be set to the context. @return {undefined} undefined
resetOptions ( options )
javascript
Famous/engine
webgl-renderers/WebGLRenderer.js
https://github.com/Famous/engine/blob/master/webgl-renderers/WebGLRenderer.js
MIT
function Texture(gl, options) { options = options || {}; this.id = gl.createTexture(); this.width = options.width || 0; this.height = options.height || 0; this.mipmap = options.mipmap; this.format = options.format || 'RGBA'; this.type = options.type || 'UNSIGNED_BYTE'; this.gl = gl; this.bind(); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, options.flipYWebgl || false); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, options.premultiplyAlphaWebgl || false); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl[options.magFilter] || gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl[options.minFilter] || gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl[options.wrapS] || gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl[options.wrapT] || gl.CLAMP_TO_EDGE); }
Texture is a private class that stores image data to be accessed from a shader or used as a render target. @class Texture @constructor @param {GL} gl GL @param {Object} options Options @return {undefined} undefined
Texture ( gl , options )
javascript
Famous/engine
webgl-renderers/Texture.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Texture.js
MIT
Texture.prototype.bind = function bind() { this.gl.bindTexture(this.gl.TEXTURE_2D, this.id); return this; };
Binds this texture as the selected target. @method @return {Object} Current texture instance.
bind ( )
javascript
Famous/engine
webgl-renderers/Texture.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Texture.js
MIT
Texture.prototype.unbind = function unbind() { this.gl.bindTexture(this.gl.TEXTURE_2D, null); return this; };
Erases the texture data in the given texture slot. @method @return {Object} Current texture instance.
unbind ( )
javascript
Famous/engine
webgl-renderers/Texture.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Texture.js
MIT
Texture.prototype.setImage = function setImage(img) { this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl[this.format], this.gl[this.format], this.gl[this.type], img); if (this.mipmap) this.gl.generateMipmap(this.gl.TEXTURE_2D); return this; };
Replaces the image data in the texture with the given image. @method @param {Image} img The image object to upload pixel data from. @return {Object} Current texture instance.
setImage ( img )
javascript
Famous/engine
webgl-renderers/Texture.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Texture.js
MIT
Texture.prototype.setArray = function setArray(input) { this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl[this.format], this.width, this.height, 0, this.gl[this.format], this.gl[this.type], input); return this; };
Replaces the image data in the texture with an array of arbitrary data. @method @param {Array} input Array to be set as data to texture. @return {Object} Current texture instance.
setArray ( input )
javascript
Famous/engine
webgl-renderers/Texture.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Texture.js
MIT
Texture.prototype.readBack = function readBack(x, y, width, height) { var gl = this.gl; var pixels; x = x || 0; y = y || 0; width = width || this.width; height = height || this.height; var fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.id, 0); if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) { pixels = new Uint8Array(width * height * 4); gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); } return pixels; };
Dumps the rgb-pixel contents of a texture into an array for debugging purposes @method @param {Number} x x-offset between texture coordinates and snapshot @param {Number} y y-offset between texture coordinates and snapshot @param {Number} width x-depth of the snapshot @param {Number} height y-depth of the snapshot @return {Array} An array of the pixels contained in the snapshot.
readBack ( x , y , width , height )
javascript
Famous/engine
webgl-renderers/Texture.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Texture.js
MIT
function Program(gl, options) { this.gl = gl; this.options = options || {}; this.registeredMaterials = {}; this.cachedUniforms = {}; this.uniformTypes = []; this.definitionVec4 = []; this.definitionVec3 = []; this.definitionFloat = []; this.applicationVec3 = []; this.applicationVec4 = []; this.applicationFloat = []; this.applicationVert = []; this.definitionVert = []; if (this.options.debug) { this.gl.compileShader = Debug.call(this); } this.resetProgram(); }
A class that handles interactions with the WebGL shader program used by a specific context. It manages creation of the shader program and the attached vertex and fragment shaders. It is also in charge of passing all uniforms to the WebGLContext. @class Program @constructor @param {WebGL_Context} gl Context to be used to create the shader program @param {Object} options Program options @return {undefined} undefined
Program ( gl , options )
javascript
Famous/engine
webgl-renderers/Program.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Program.js
MIT
Program.prototype.registerMaterial = function registerMaterial(name, material) { var compiled = material; var type = inputTypes[name]; var mask = masks[type]; if ((this.registeredMaterials[material._id] & mask) === mask) return this; var k; for (k in compiled.uniforms) { if (uniforms.keys.indexOf(k) === -1) { uniforms.keys.push(k); uniforms.values.push(compiled.uniforms[k]); } } for (k in compiled.varyings) { if (varyings.keys.indexOf(k) === -1) { varyings.keys.push(k); varyings.values.push(compiled.varyings[k]); } } for (k in compiled.attributes) { if (attributes.keys.indexOf(k) === -1) { attributes.keys.push(k); attributes.values.push(compiled.attributes[k]); } } this.registeredMaterials[material._id] |= mask; if (type === 'float') { this.definitionFloat.push(material.defines); this.definitionFloat.push('float fa_' + material._id + '() {\n ' + compiled.glsl + ' \n}'); this.applicationFloat.push('if (int(abs(ID)) == ' + material._id + ') return fa_' + material._id + '();'); } if (type === 'vec3') { this.definitionVec3.push(material.defines); this.definitionVec3.push('vec3 fa_' + material._id + '() {\n ' + compiled.glsl + ' \n}'); this.applicationVec3.push('if (int(abs(ID.x)) == ' + material._id + ') return fa_' + material._id + '();'); } if (type === 'vec4') { this.definitionVec4.push(material.defines); this.definitionVec4.push('vec4 fa_' + material._id + '() {\n ' + compiled.glsl + ' \n}'); this.applicationVec4.push('if (int(abs(ID.x)) == ' + material._id + ') return fa_' + material._id + '();'); } if (type === 'vert') { this.definitionVert.push(material.defines); this.definitionVert.push('vec3 fa_' + material._id + '() {\n ' + compiled.glsl + ' \n}'); this.applicationVert.push('if (int(abs(ID.x)) == ' + material._id + ') return fa_' + material._id + '();'); } return this.resetProgram(); };
Determines whether a material has already been registered to the shader program. @method @param {String} name Name of target input of material. @param {Object} material Compiled material object being verified. @return {Program} this Current program.
registerMaterial ( name , material )
javascript
Famous/engine
webgl-renderers/Program.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Program.js
MIT
Program.prototype.resetProgram = function resetProgram() { var vertexHeader = [header]; var fragmentHeader = [header]; var fragmentSource; var vertexSource; var program; var name; var value; var i; this.uniformLocations = []; this.attributeLocations = {}; this.uniformTypes = {}; this.attributeNames = clone(attributes.keys); this.attributeValues = clone(attributes.values); this.varyingNames = clone(varyings.keys); this.varyingValues = clone(varyings.values); this.uniformNames = clone(uniforms.keys); this.uniformValues = clone(uniforms.values); this.cachedUniforms = {}; fragmentHeader.push('uniform sampler2D u_textures[7];\n'); if (this.applicationVert.length) { vertexHeader.push('uniform sampler2D u_textures[7];\n'); } for(i = 0; i < this.uniformNames.length; i++) { name = this.uniformNames[i]; value = this.uniformValues[i]; vertexHeader.push('uniform ' + TYPES[value.length] + name + ';\n'); fragmentHeader.push('uniform ' + TYPES[value.length] + name + ';\n'); } for(i = 0; i < this.attributeNames.length; i++) { name = this.attributeNames[i]; value = this.attributeValues[i]; vertexHeader.push('attribute ' + TYPES[value.length] + name + ';\n'); } for(i = 0; i < this.varyingNames.length; i++) { name = this.varyingNames[i]; value = this.varyingValues[i]; vertexHeader.push('varying ' + TYPES[value.length] + name + ';\n'); fragmentHeader.push('varying ' + TYPES[value.length] + name + ';\n'); } vertexSource = vertexHeader.join('') + vertexWrapper .replace('#vert_definitions', this.definitionVert.join('\n')) .replace('#vert_applications', this.applicationVert.join('\n')); fragmentSource = fragmentHeader.join('') + fragmentWrapper .replace('#vec3_definitions', this.definitionVec3.join('\n')) .replace('#vec3_applications', this.applicationVec3.join('\n')) .replace('#vec4_definitions', this.definitionVec4.join('\n')) .replace('#vec4_applications', this.applicationVec4.join('\n')) .replace('#float_definitions', this.definitionFloat.join('\n')) .replace('#float_applications', this.applicationFloat.join('\n')); program = this.gl.createProgram(); this.gl.attachShader( program, this.compileShader(this.gl.createShader(VERTEX_SHADER), vertexSource) ); this.gl.attachShader( program, this.compileShader(this.gl.createShader(FRAGMENT_SHADER), fragmentSource) ); this.gl.linkProgram(program); if (! this.gl.getProgramParameter(program, this.gl.LINK_STATUS)) { console.error('link error: ' + this.gl.getProgramInfoLog(program)); this.program = null; } else { this.program = program; this.gl.useProgram(this.program); } this.setUniforms(this.uniformNames, this.uniformValues); var textureLocation = this.gl.getUniformLocation(this.program, 'u_textures[0]'); this.gl.uniform1iv(textureLocation, [0, 1, 2, 3, 4, 5, 6]); return this; };
Clears all cached uniforms and attribute locations. Assembles new fragment and vertex shaders and based on material from currently registered materials. Attaches said shaders to new shader program and upon success links program to the WebGL context. @method @return {Program} Current program.
resetProgram ( )
javascript
Famous/engine
webgl-renderers/Program.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Program.js
MIT
Program.prototype.uniformIsCached = function(targetName, value) { if(this.cachedUniforms[targetName] == null) { if (value.length) { this.cachedUniforms[targetName] = new Float32Array(value); } else { this.cachedUniforms[targetName] = value; } return false; } else if (value.length) { var i = value.length; while (i--) { if(value[i] !== this.cachedUniforms[targetName][i]) { i = value.length; while(i--) this.cachedUniforms[targetName][i] = value[i]; return false; } } } else if (this.cachedUniforms[targetName] !== value) { this.cachedUniforms[targetName] = value; return false; } return true; };
Compares the value of the input uniform value against the cached value stored on the Program class. Updates and creates new entries in the cache when necessary. @method @param {String} targetName Key of uniform spec being evaluated. @param {Number|Array} value Value of uniform spec being evaluated. @return {Boolean} boolean Indicating whether the uniform being set is cached.
Program.prototype.uniformIsCached ( targetName , value )
javascript
Famous/engine
webgl-renderers/Program.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Program.js
MIT
Program.prototype.setUniforms = function (uniformNames, uniformValue) { var gl = this.gl; var location; var value; var name; var len; var i; if (!this.program) return this; len = uniformNames.length; for (i = 0; i < len; i++) { name = uniformNames[i]; value = uniformValue[i]; // Retreive the cached location of the uniform, // requesting a new location from the WebGL context // if it does not yet exist. location = this.uniformLocations[name]; if (location === null) continue; if (location === undefined) { location = gl.getUniformLocation(this.program, name); this.uniformLocations[name] = location; } // Check if the value is already set for the // given uniform. if (this.uniformIsCached(name, value)) continue; // Determine the correct function and pass the uniform // value to WebGL. if (!this.uniformTypes[name]) { this.uniformTypes[name] = this.getUniformTypeFromValue(value); } // Call uniform setter function on WebGL context with correct value switch (this.uniformTypes[name]) { case 'uniform4fv': gl.uniform4fv(location, value); break; case 'uniform3fv': gl.uniform3fv(location, value); break; case 'uniform2fv': gl.uniform2fv(location, value); break; case 'uniform1fv': gl.uniform1fv(location, value); break; case 'uniform1f' : gl.uniform1f(location, value); break; case 'uniformMatrix3fv': gl.uniformMatrix3fv(location, false, value); break; case 'uniformMatrix4fv': gl.uniformMatrix4fv(location, false, value); break; } } return this; };
Handles all passing of uniforms to WebGL drawing context. This function will find the uniform location and then, based on a type inferred from the javascript value of the uniform, it will call the appropriate function to pass the uniform to WebGL. Finally, setUniforms will iterate through the passed in shaderChunks (if any) and set the appropriate uniforms to specify which chunks to use. @method @param {Array} uniformNames Array containing the keys of all uniforms to be set. @param {Array} uniformValue Array containing the values of all uniforms to be set. @return {Program} Current program.
Program.prototype.setUniforms ( uniformNames , uniformValue )
javascript
Famous/engine
webgl-renderers/Program.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Program.js
MIT
Program.prototype.getUniformTypeFromValue = function getUniformTypeFromValue(value) { if (Array.isArray(value) || value instanceof Float32Array) { switch (value.length) { case 1: return 'uniform1fv'; case 2: return 'uniform2fv'; case 3: return 'uniform3fv'; case 4: return 'uniform4fv'; case 9: return 'uniformMatrix3fv'; case 16: return 'uniformMatrix4fv'; } } else if (!isNaN(parseFloat(value)) && isFinite(value)) { return 'uniform1f'; } throw 'cant load uniform "' + name + '" with value:' + JSON.stringify(value); };
Infers uniform setter function to be called on the WebGL context, based on an input value. @method @param {Number|Array} value Value from which uniform type is inferred. @return {String} Name of uniform function for given value.
getUniformTypeFromValue ( value )
javascript
Famous/engine
webgl-renderers/Program.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Program.js
MIT
Program.prototype.compileShader = function compileShader(shader, source) { var i = 1; this.gl.shaderSource(shader, source); this.gl.compileShader(shader); if (!this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS)) { console.error('compile error: ' + this.gl.getShaderInfoLog(shader)); console.error('1: ' + source.replace(/\n/g, function () { return '\n' + (i+=1) + ': '; })); } return shader; };
Adds shader source to shader and compiles the input shader. Checks compile status and logs error if necessary. @method @param {Object} shader Program to be compiled. @param {String} source Source to be used in the shader. @return {Object} Compiled shader.
compileShader ( shader , source )
javascript
Famous/engine
webgl-renderers/Program.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Program.js
MIT
function radixSort(list, registry) { var pass = 0; var out = []; var i, j, k, n, div, offset, swap, id, sum, tsum, size; passCount = ((32 / radixBits) + 0.999999999999999) | 0; for (i = 0, n = maxRadix * passCount; i < n; i++) buckets[i] = 0; for (i = 0, n = list.length; i < n; i++) { div = floatToInt(comp(list, registry, i)); div ^= div >> 31 | 0x80000000; for (j = 0, k = 0; j < maxOffset; j += maxRadix, k += radixBits) { buckets[j + (div >>> k & radixMask)]++; } buckets[j + (div >>> k & lastMask)]++; } for (j = 0; j <= maxOffset; j += maxRadix) { for (id = j, sum = 0; id < j + maxRadix; id++) { tsum = buckets[id] + sum; buckets[id] = sum - 1; sum = tsum; } } if (--passCount) { for (i = 0, n = list.length; i < n; i++) { div = floatToInt(comp(list, registry, i)); out[++buckets[div & radixMask]] = mutator(list, registry, i, div ^= div >> 31 | 0x80000000); } swap = out; out = list; list = swap; while (++pass < passCount) { for (i = 0, n = list.length, offset = pass * maxRadix, size = pass * radixBits; i < n; i++) { div = floatToInt(comp(list, registry, i)); out[++buckets[offset + (div >>> size & radixMask)]] = list[i]; } swap = out; out = list; list = swap; } } for (i = 0, n = list.length, offset = pass * maxRadix, size = pass * radixBits; i < n; i++) { div = floatToInt(comp(list, registry, i)); out[++buckets[offset + (div >>> size & lastMask)]] = mutator(list, registry, i, div ^ (~div >> 31 | 0x80000000)); clean(list, registry, i); } return out; }
Sorts an array of mesh IDs according to their z-depth. @param {Array} list An array of meshes. @param {Object} registry A registry mapping the path names to meshes. @return {Array} An array of the meshes sorted by z-depth.
radixSort ( list , registry )
javascript
Famous/engine
webgl-renderers/radixSort.js
https://github.com/Famous/engine/blob/master/webgl-renderers/radixSort.js
MIT
function Debug() { return _augmentFunction( this.gl.compileShader, function(shader) { if (!this.getShaderParameter(shader, this.COMPILE_STATUS)) { var errors = this.getShaderInfoLog(shader); var source = this.getShaderSource(shader); _processErrors(errors, source); } } ); }
Takes the original rendering contexts' compiler function and augments it with added functionality for parsing and displaying errors. @method @returns {Function} Augmented function
Debug ( )
javascript
Famous/engine
webgl-renderers/Debug.js
https://github.com/Famous/engine/blob/master/webgl-renderers/Debug.js
MIT
DOMElement.prototype.getValue = function getValue() { return { classes: this._classes, styles: this._styles, attributes: this._attributes, content: this._content, id: this._attributes.id, tagName: this._tagName }; };
Serializes the state of the DOMElement. @method @return {Object} serialized interal state
getValue ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onUpdate = function onUpdate () { var node = this._node; var queue = this._changeQueue; var len = queue.length; if (len && node) { node.sendDrawCommand(Commands.WITH); node.sendDrawCommand(node.getLocation()); while (len--) node.sendDrawCommand(queue.shift()); if (this._requestRenderSize) { node.sendDrawCommand(Commands.DOM_RENDER_SIZE); node.sendDrawCommand(node.getLocation()); this._requestRenderSize = false; } } this._requestingUpdate = false; };
Method to be invoked by the node as soon as an update occurs. This allows the DOMElement renderable to dynamically react to state changes on the Node. This flushes the internal draw command queue by sending individual commands to the node using `sendDrawCommand`. @method @return {undefined} undefined
onUpdate ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onMount = function onMount(node, id) { this._node = node; this._id = id; this._UIEvents = node.getUIEvents().slice(0); TransformSystem.makeBreakPointAt(node.getLocation()); this.onSizeModeChange.apply(this, node.getSizeMode()); this.draw(); this.setAttribute('data-fa-path', node.getLocation()); };
Method to be invoked by the Node as soon as the node (or any of its ancestors) is being mounted. @method onMount @param {Node} node Parent node to which the component should be added. @param {String} id Path at which the component (or node) is being attached. The path is being set on the actual DOMElement as a `data-fa-path`-attribute. @return {undefined} undefined
onMount ( node , id )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onDismount = function onDismount() { this.setProperty('display', 'none'); this.setAttribute('data-fa-path', ''); this.setCutoutState(false); this.onUpdate(); this._initialized = false; };
Method to be invoked by the Node as soon as the node is being dismounted either directly or by dismounting one of its ancestors. @method @return {undefined} undefined
onDismount ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onShow = function onShow() { this.setProperty('display', 'block'); };
Method to be invoked by the node as soon as the DOMElement is being shown. This results into the DOMElement setting the `display` property to `block` and therefore visually showing the corresponding DOMElement (again). @method @return {undefined} undefined
onShow ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onHide = function onHide() { this.setProperty('display', 'none'); };
Method to be invoked by the node as soon as the DOMElement is being hidden. This results into the DOMElement setting the `display` property to `none` and therefore visually hiding the corresponding DOMElement (again). @method @return {undefined} undefined
onHide ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.setCutoutState = function setCutoutState (usesCutout) { if (this._initialized) this._changeQueue.push(Commands.GL_CUTOUT_STATE, usesCutout); if (!this._requestingUpdate) this._requestUpdate(); return this; };
Enables or disables WebGL 'cutout' for this element, which affects how the element is layered with WebGL objects in the scene. @method @param {Boolean} usesCutout The presence of a WebGL 'cutout' for this element. @return {DOMElement} this
setCutoutState ( usesCutout )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onTransformChange = function onTransformChange (transform) { this._changeQueue.push(Commands.CHANGE_TRANSFORM); transform = transform.getLocalTransform(); for (var i = 0, len = transform.length ; i < len ; i++) this._changeQueue.push(transform[i]); if (!this._requestingUpdate) this._requestUpdate(); };
Method to be invoked by the node as soon as the transform matrix associated with the node changes. The DOMElement will react to transform changes by sending `CHANGE_TRANSFORM` commands to the `DOMRenderer`. @method @param {Float32Array} transform The final transform matrix @return {undefined} undefined
onTransformChange ( transform )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onOpacityChange = function onOpacityChange(opacity) { return this.setProperty('opacity', opacity); };
Method to be invoked by the node as soon as its opacity changes @method @param {Number} opacity The new opacity, as a scalar from 0 to 1 @return {DOMElement} this
onOpacityChange ( opacity )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onAddUIEvent = function onAddUIEvent(uiEvent) { if (this._UIEvents.indexOf(uiEvent) === -1) { this._subscribe(uiEvent); this._UIEvents.push(uiEvent); } else if (this._inDraw) { this._subscribe(uiEvent); } return this; };
Method to be invoked by the node as soon as a new UIEvent is being added. This results into an `ADD_EVENT_LISTENER` command being sent. @param {String} uiEvent uiEvent to be subscribed to (e.g. `click`) @return {undefined} undefined
onAddUIEvent ( uiEvent )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onRemoveUIEvent = function onRemoveUIEvent(UIEvent) { var index = this._UIEvents.indexOf(UIEvent); if (index !== -1) { this._unsubscribe(UIEvent); this._UIEvents.splice(index, 1); } else if (this._inDraw) { this._unsubscribe(UIEvent); } return this; };
Method to be invoked by the node as soon as a UIEvent is removed from the node. This results into an `UNSUBSCRIBE` command being sent. @param {String} UIEvent UIEvent to be removed (e.g. `mousedown`) @return {undefined} undefined
onRemoveUIEvent ( UIEvent )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype._subscribe = function _subscribe (uiEvent) { if (this._initialized) { this._changeQueue.push(Commands.SUBSCRIBE, uiEvent); } if (!this._requestingUpdate) this._requestUpdate(); };
Appends an `SUBSCRIBE` command to the command queue. @method @private @param {String} uiEvent Event type (e.g. `click`) @return {undefined} undefined
_subscribe ( uiEvent )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.preventDefault = function preventDefault (uiEvent) { if (this._initialized) { this._changeQueue.push(Commands.PREVENT_DEFAULT, uiEvent); } if (!this._requestingUpdate) this._requestUpdate(); };
When running in a worker, the browser's default action for specific events can't be prevented on a case by case basis (via `e.preventDefault()`). Instead this function should be used to register an event to be prevented by default. @method @param {String} uiEvent UI Event (e.g. wheel) for which to prevent the browser's default action (e.g. form submission, scrolling) @return {undefined} undefined
preventDefault ( uiEvent )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.allowDefault = function allowDefault (uiEvent) { if (this._initialized) { this._changeQueue.push(Commands.ALLOW_DEFAULT, uiEvent); } if (!this._requestingUpdate) this._requestUpdate(); };
Opposite of {@link DOMElement#preventDefault}. No longer prevent the browser's default action on subsequent events of this type. @method @param {type} uiEvent UI Event previously registered using {@link DOMElement#preventDefault}. @return {undefined} undefined
allowDefault ( uiEvent )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype._unsubscribe = function _unsubscribe (UIEvent) { if (this._initialized) { this._changeQueue.push(Commands.UNSUBSCRIBE, UIEvent); } if (!this._requestingUpdate) this._requestUpdate(); };
Appends an `UNSUBSCRIBE` command to the command queue. @method @private @param {String} UIEvent Event type (e.g. `click`) @return {undefined} undefined
_unsubscribe ( UIEvent )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onSizeModeChange = function onSizeModeChange(x, y, z) { if (x === Size.RENDER || y === Size.RENDER || z === Size.RENDER) { this._renderSized = true; this._requestRenderSize = true; } var size = this._node.getSize(); this.onSizeChange(size[0], size[1]); };
Method to be invoked by the node as soon as the underlying size mode changes. This results into the size being fetched from the node in order to update the actual, rendered size. @method @param {Number} x the sizing mode in use for determining size in the x direction @param {Number} y the sizing mode in use for determining size in the y direction @param {Number} z the sizing mode in use for determining size in the z direction @return {undefined} undefined
onSizeModeChange ( x , y , z )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.getRenderSize = function getRenderSize() { return this._renderSize; };
Method to be retrieve the rendered size of the DOM element that is drawn for this node. @method @return {Array} size of the rendered DOM element in pixels
getRenderSize ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype._requestUpdate = function _requestUpdate() { if (!this._requestingUpdate && this._id) { this._node.requestUpdate(this._id); this._requestingUpdate = true; } };
Method to have the component request an update from its Node @method @private @return {undefined} undefined
_requestUpdate ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.init = function init () { this._changeQueue.push(Commands.INIT_DOM, this._tagName); this._initialized = true; this.onTransformChange(TransformSystem.get(this._node.getLocation())); var size = this._node.getSize(); this.onSizeChange(size[0], size[1]); if (!this._requestingUpdate) this._requestUpdate(); };
Initializes the DOMElement by sending the `INIT_DOM` command. This creates or reallocates a new Element in the actual DOM hierarchy. @method @return {undefined} undefined
init ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.setId = function setId (id) { this.setAttribute('id', id); return this; };
Sets the id attribute of the DOMElement. @method @param {String} id New id to be set @return {DOMElement} this
setId ( id )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.addClass = function addClass (value) { if (this._classes.indexOf(value) < 0) { if (this._initialized) this._changeQueue.push(Commands.ADD_CLASS, value); this._classes.push(value); if (!this._requestingUpdate) this._requestUpdate(); if (this._renderSized) this._requestRenderSize = true; return this; } if (this._inDraw) { if (this._initialized) this._changeQueue.push(Commands.ADD_CLASS, value); if (!this._requestingUpdate) this._requestUpdate(); } return this; };
Adds a new class to the internal class list of the underlying Element in the DOM. @method @param {String} value New class name to be added @return {DOMElement} this
addClass ( value )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.removeClass = function removeClass (value) { var index = this._classes.indexOf(value); if (index < 0) return this; this._changeQueue.push(Commands.REMOVE_CLASS, value); this._classes.splice(index, 1); if (!this._requestingUpdate) this._requestUpdate(); return this; };
Removes a class from the DOMElement's classList. @method @param {String} value Class name to be removed @return {DOMElement} this
removeClass ( value )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.hasClass = function hasClass (value) { return this._classes.indexOf(value) !== -1; };
Checks if the DOMElement has the passed in class. @method @param {String} value The class name @return {Boolean} Boolean value indicating whether the passed in class name is in the DOMElement's class list.
hasClass ( value )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.setAttribute = function setAttribute (name, value) { if (this._attributes[name] !== value || this._inDraw) { this._attributes[name] = value; if (this._initialized) this._changeQueue.push(Commands.CHANGE_ATTRIBUTE, name, value); if (!this._requestUpdate) this._requestUpdate(); } return this; };
Sets an attribute of the DOMElement. @method @param {String} name Attribute key (e.g. `src`) @param {String} value Attribute value (e.g. `http://famo.us`) @return {DOMElement} this
setAttribute ( name , value )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.setProperty = function setProperty (name, value) { if (this._styles[name] !== value || this._inDraw) { this._styles[name] = value; if (this._initialized) this._changeQueue.push(Commands.CHANGE_PROPERTY, name, value); if (!this._requestingUpdate) this._requestUpdate(); if (this._renderSized) this._requestRenderSize = true; } return this; };
Sets a CSS property @chainable @param {String} name Name of the CSS rule (e.g. `background-color`) @param {String} value Value of CSS property (e.g. `red`) @return {DOMElement} this
setProperty ( name , value )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.setContent = function setContent (content) { if (this._content !== content || this._inDraw) { this._content = content; if (this._initialized) this._changeQueue.push(Commands.CHANGE_CONTENT, content); if (!this._requestingUpdate) this._requestUpdate(); if (this._renderSized) this._requestRenderSize = true; } return this; };
Sets the content of the DOMElement. This is using `innerHTML`, escaping user generated content is therefore essential for security purposes. @method @param {String} content Content to be set using `.innerHTML = ...` @return {DOMElement} this
setContent ( content )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.on = function on (event, listener) { return this._callbacks.on(event, listener); };
Subscribes to a DOMElement using. @method on @param {String} event The event type (e.g. `click`). @param {Function} listener Handler function for the specified event type in which the payload event object will be passed into. @return {Function} A function to call if you want to remove the callback
on ( event , listener )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onReceive = function onReceive (event, payload) { if (event === 'resize') { this._renderSize[0] = payload.val[0]; this._renderSize[1] = payload.val[1]; if (!this._requestingUpdate) this._requestUpdate(); } this._callbacks.trigger(event, payload); };
Function to be invoked by the Node whenever an event is being received. There are two different ways to subscribe for those events: 1. By overriding the onReceive method (and possibly using `switch` in order to differentiate between the different event types). 2. By using DOMElement and using the built-in CallbackStore. @method @param {String} event Event type (e.g. `click`) @param {Object} payload Event object. @return {undefined} undefined
onReceive ( event , payload )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.draw = function draw() { var key; var i; var len; this._inDraw = true; this.init(); for (i = 0, len = this._classes.length ; i < len ; i++) this.addClass(this._classes[i]); if (this._content) this.setContent(this._content); for (key in this._styles) if (this._styles[key] != null) this.setProperty(key, this._styles[key]); for (key in this._attributes) if (this._attributes[key] != null) this.setAttribute(key, this._attributes[key]); for (i = 0, len = this._UIEvents.length ; i < len ; i++) this.onAddUIEvent(this._UIEvents[i]); this._inDraw = false; };
The draw function is being used in order to allow mutating the DOMElement before actually mounting the corresponding node. @method @private @return {undefined} undefined
draw ( )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
DOMElement.prototype.onSizeChange = function onSizeChange(x, y) { var sizeMode = this._node.getSizeMode(); var sizedX = sizeMode[0] !== Size.RENDER; var sizedY = sizeMode[1] !== Size.RENDER; if (this._initialized) this._changeQueue.push(Commands.CHANGE_SIZE, sizedX ? x : sizedX, sizedY ? y : sizedY); if (!this._requestingUpdate) this._requestUpdate(); return this; }; /** * Method to be invoked by the node as soon as its opacity changes * * @method * * @param {Number} opacity The new opacity, as a scalar from 0 to 1 * * @return {DOMElement} this */ DOMElement.prototype.onOpacityChange = function onOpacityChange(opacity) { return this.setProperty('opacity', opacity); }; /** * Method to be invoked by the node as soon as a new UIEvent is being added. * This results into an `ADD_EVENT_LISTENER` command being sent. * * @param {String} uiEvent uiEvent to be subscribed to (e.g. `click`) * * @return {undefined} undefined */ DOMElement.prototype.onAddUIEvent = function onAddUIEvent(uiEvent) { if (this._UIEvents.indexOf(uiEvent) === -1) { this._subscribe(uiEvent); this._UIEvents.push(uiEvent); } else if (this._inDraw) { this._subscribe(uiEvent); } return this; }; /** * Method to be invoked by the node as soon as a UIEvent is removed from * the node. This results into an `UNSUBSCRIBE` command being sent. * * @param {String} UIEvent UIEvent to be removed (e.g. `mousedown`) * * @return {undefined} undefined */ DOMElement.prototype.onRemoveUIEvent = function onRemoveUIEvent(UIEvent) { var index = this._UIEvents.indexOf(UIEvent); if (index !== -1) { this._unsubscribe(UIEvent); this._UIEvents.splice(index, 1); } else if (this._inDraw) { this._unsubscribe(UIEvent); } return this; }; /** * Appends an `SUBSCRIBE` command to the command queue. * * @method * @private * * @param {String} uiEvent Event type (e.g. `click`) * * @return {undefined} undefined */ DOMElement.prototype._subscribe = function _subscribe (uiEvent) { if (this._initialized) { this._changeQueue.push(Commands.SUBSCRIBE, uiEvent); } if (!this._requestingUpdate) this._requestUpdate(); }; /** * When running in a worker, the browser's default action for specific events * can't be prevented on a case by case basis (via `e.preventDefault()`). * Instead this function should be used to register an event to be prevented by * default. * * @method * * @param {String} uiEvent UI Event (e.g. wheel) for which to prevent the * browser's default action (e.g. form submission, * scrolling) * @return {undefined} undefined */ DOMElement.prototype.preventDefault = function preventDefault (uiEvent) { if (this._initialized) { this._changeQueue.push(Commands.PREVENT_DEFAULT, uiEvent); } if (!this._requestingUpdate) this._requestUpdate(); }; /** * Opposite of {@link DOMElement#preventDefault}. No longer prevent the * browser's default action on subsequent events of this type. * * @method * * @param {type} uiEvent UI Event previously registered using * {@link DOMElement#preventDefault}. * @return {undefined} undefined */ DOMElement.prototype.allowDefault = function allowDefault (uiEvent) { if (this._initialized) { this._changeQueue.push(Commands.ALLOW_DEFAULT, uiEvent); } if (!this._requestingUpdate) this._requestUpdate(); }; /** * Appends an `UNSUBSCRIBE` command to the command queue. * * @method * @private * * @param {String} UIEvent Event type (e.g. `click`) * * @return {undefined} undefined */ DOMElement.prototype._unsubscribe = function _unsubscribe (UIEvent) { if (this._initialized) { this._changeQueue.push(Commands.UNSUBSCRIBE, UIEvent); } if (!this._requestingUpdate) this._requestUpdate(); }; /** * Method to be invoked by the node as soon as the underlying size mode * changes. This results into the size being fetched from the node in * order to update the actual, rendered size. * * @method * * @param {Number} x the sizing mode in use for determining size in the x direction * @param {Number} y the sizing mode in use for determining size in the y direction * @param {Number} z the sizing mode in use for determining size in the z direction * * @return {undefined} undefined */ DOMElement.prototype.onSizeModeChange = function onSizeModeChange(x, y, z) { if (x === Size.RENDER || y === Size.RENDER || z === Size.RENDER) { this._renderSized = true; this._requestRenderSize = true; } var size = this._node.getSize(); this.onSizeChange(size[0], size[1]); }; /** * Method to be retrieve the rendered size of the DOM element that is * drawn for this node. * * @method * * @return {Array} size of the rendered DOM element in pixels */ DOMElement.prototype.getRenderSize = function getRenderSize() { return this._renderSize; }; /** * Method to have the component request an update from its Node * * @method * @private * * @return {undefined} undefined */ DOMElement.prototype._requestUpdate = function _requestUpdate() { if (!this._requestingUpdate && this._id) { this._node.requestUpdate(this._id); this._requestingUpdate = true; } }; /** * Initializes the DOMElement by sending the `INIT_DOM` command. This creates * or reallocates a new Element in the actual DOM hierarchy. * * @method * * @return {undefined} undefined */ DOMElement.prototype.init = function init () { this._changeQueue.push(Commands.INIT_DOM, this._tagName); this._initialized = true; this.onTransformChange(TransformSystem.get(this._node.getLocation())); var size = this._node.getSize(); this.onSizeChange(size[0], size[1]); if (!this._requestingUpdate) this._requestUpdate(); }; /** * Sets the id attribute of the DOMElement. * * @method * * @param {String} id New id to be set * * @return {DOMElement} this */ DOMElement.prototype.setId = function setId (id) { this.setAttribute('id', id); return this; }; /** * Adds a new class to the internal class list of the underlying Element in the * DOM. * * @method * * @param {String} value New class name to be added * * @return {DOMElement} this */ DOMElement.prototype.addClass = function addClass (value) { if (this._classes.indexOf(value) < 0) { if (this._initialized) this._changeQueue.push(Commands.ADD_CLASS, value); this._classes.push(value); if (!this._requestingUpdate) this._requestUpdate(); if (this._renderSized) this._requestRenderSize = true; return this; } if (this._inDraw) { if (this._initialized) this._changeQueue.push(Commands.ADD_CLASS, value); if (!this._requestingUpdate) this._requestUpdate(); } return this; }; /** * Removes a class from the DOMElement's classList. * * @method * * @param {String} value Class name to be removed * * @return {DOMElement} this */ DOMElement.prototype.removeClass = function removeClass (value) { var index = this._classes.indexOf(value); if (index < 0) return this; this._changeQueue.push(Commands.REMOVE_CLASS, value); this._classes.splice(index, 1); if (!this._requestingUpdate) this._requestUpdate(); return this; }; /** * Checks if the DOMElement has the passed in class. * * @method * * @param {String} value The class name * * @return {Boolean} Boolean value indicating whether the passed in class name is in the DOMElement's class list. */ DOMElement.prototype.hasClass = function hasClass (value) { return this._classes.indexOf(value) !== -1; }; /** * Sets an attribute of the DOMElement. * * @method * * @param {String} name Attribute key (e.g. `src`) * @param {String} value Attribute value (e.g. `http://famo.us`) * * @return {DOMElement} this */ DOMElement.prototype.setAttribute = function setAttribute (name, value) { if (this._attributes[name] !== value || this._inDraw) { this._attributes[name] = value; if (this._initialized) this._changeQueue.push(Commands.CHANGE_ATTRIBUTE, name, value); if (!this._requestUpdate) this._requestUpdate(); } return this; }; /** * Sets a CSS property * * @chainable * * @param {String} name Name of the CSS rule (e.g. `background-color`) * @param {String} value Value of CSS property (e.g. `red`) * * @return {DOMElement} this */ DOMElement.prototype.setProperty = function setProperty (name, value) { if (this._styles[name] !== value || this._inDraw) { this._styles[name] = value; if (this._initialized) this._changeQueue.push(Commands.CHANGE_PROPERTY, name, value); if (!this._requestingUpdate) this._requestUpdate(); if (this._renderSized) this._requestRenderSize = true; } return this; }; /** * Sets the content of the DOMElement. This is using `innerHTML`, escaping user * generated content is therefore essential for security purposes. * * @method * * @param {String} content Content to be set using `.innerHTML = ...` * * @return {DOMElement} this */ DOMElement.prototype.setContent = function setContent (content) { if (this._content !== content || this._inDraw) { this._content = content; if (this._initialized) this._changeQueue.push(Commands.CHANGE_CONTENT, content); if (!this._requestingUpdate) this._requestUpdate(); if (this._renderSized) this._requestRenderSize = true; } return this; }; /** * Subscribes to a DOMElement using. * * @method on * * @param {String} event The event type (e.g. `click`). * @param {Function} listener Handler function for the specified event type * in which the payload event object will be * passed into. * * @return {Function} A function to call if you want to remove the callback */ DOMElement.prototype.on = function on (event, listener) { return this._callbacks.on(event, listener); }; /** * Function to be invoked by the Node whenever an event is being received. * There are two different ways to subscribe for those events: * * 1. By overriding the onReceive method (and possibly using `switch` in order * to differentiate between the different event types). * 2. By using DOMElement and using the built-in CallbackStore. * * @method * * @param {String} event Event type (e.g. `click`) * @param {Object} payload Event object. * * @return {undefined} undefined */ DOMElement.prototype.onReceive = function onReceive (event, payload) { if (event === 'resize') { this._renderSize[0] = payload.val[0]; this._renderSize[1] = payload.val[1]; if (!this._requestingUpdate) this._requestUpdate(); } this._callbacks.trigger(event, payload); }; /** * The draw function is being used in order to allow mutating the DOMElement * before actually mounting the corresponding node. * * @method * @private * * @return {undefined} undefined */ DOMElement.prototype.draw = function draw() { var key; var i; var len; this._inDraw = true; this.init(); for (i = 0, len = this._classes.length ; i < len ; i++) this.addClass(this._classes[i]); if (this._content) this.setContent(this._content); for (key in this._styles) if (this._styles[key] != null) this.setProperty(key, this._styles[key]); for (key in this._attributes) if (this._attributes[key] != null) this.setAttribute(key, this._attributes[key]); for (i = 0, len = this._UIEvents.length ; i < len ; i++) this.onAddUIEvent(this._UIEvents[i]); this._inDraw = false; }; module.exports = DOMElement;
Method to be invoked by the node as soon as its computed size changes. @method @param {Number} x width of the Node the DOMElement is attached to @param {Number} y height of the Node the DOMElement is attached to @return {DOMElement} this
onSizeChange ( x , y )
javascript
Famous/engine
dom-renderables/DOMElement.js
https://github.com/Famous/engine/blob/master/dom-renderables/DOMElement.js
MIT
function Quaternion(w, x, y, z) { this.w = w || 1; this.x = x || 0; this.y = y || 0; this.z = z || 0; }
A vector-like object used to represent rotations. If theta is the angle of rotation, and (x', y', z') is a normalized vector representing the axis of rotation, then w = cos(theta/2), x = sin(theta/2)*x', y = sin(theta/2)*y', and z = sin(theta/2)*z'. @class Quaternion @param {Number} w The w component. @param {Number} x The x component. @param {Number} y The y component. @param {Number} z The z component.
Quaternion ( w , x , y , z )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.multiply = function multiply(q) { var x1 = this.x; var y1 = this.y; var z1 = this.z; var w1 = this.w; var x2 = q.x; var y2 = q.y; var z2 = q.z; var w2 = q.w || 0; this.w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2; this.x = x1 * w2 + x2 * w1 + y2 * z1 - y1 * z2; this.y = y1 * w2 + y2 * w1 + x1 * z2 - x2 * z1; this.z = z1 * w2 + z2 * w1 + x2 * y1 - x1 * y2; return this; };
Multiply the current Quaternion by input Quaternion q. Left-handed multiplication. @method @param {Quaternion} q The Quaternion to multiply by on the right. @return {Quaternion} this
multiply ( q )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.leftMultiply = function leftMultiply(q) { var x1 = q.x; var y1 = q.y; var z1 = q.z; var w1 = q.w || 0; var x2 = this.x; var y2 = this.y; var z2 = this.z; var w2 = this.w; this.w = w1*w2 - x1*x2 - y1*y2 - z1*z2; this.x = x1*w2 + x2*w1 + y2*z1 - y1*z2; this.y = y1*w2 + y2*w1 + x1*z2 - x2*z1; this.z = z1*w2 + z2*w1 + x2*y1 - x1*y2; return this; };
Multiply the current Quaternion by input Quaternion q on the left, i.e. q * this. Left-handed multiplication. @method @param {Quaternion} q The Quaternion to multiply by on the left. @return {Quaternion} this
leftMultiply ( q )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.rotateVector = function rotateVector(v, output) { var cw = this.w; var cx = -this.x; var cy = -this.y; var cz = -this.z; var vx = v.x; var vy = v.y; var vz = v.z; var tw = -cx * vx - cy * vy - cz * vz; var tx = vx * cw + vy * cz - cy * vz; var ty = vy * cw + cx * vz - vx * cz; var tz = vz * cw + vx * cy - cx * vy; var w = cw; var x = -cx; var y = -cy; var z = -cz; output.x = tx * w + x * tw + y * tz - ty * z; output.y = ty * w + y * tw + tx * z - x * tz; output.z = tz * w + z * tw + x * ty - tx * y; return output; };
Apply the current Quaternion to input Vec3 v, according to v' = ~q * v * q. @method @param {Vec3} v The reference Vec3. @param {Vec3} output Vec3 in which to place the result. @return {Vec3} The rotated version of the Vec3.
rotateVector ( v , output )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.invert = function invert() { this.w = -this.w; this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; };
Invert the current Quaternion. @method @return {Quaternion} this
invert ( )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.conjugate = function conjugate() { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; };
Conjugate the current Quaternion. @method @return {Quaternion} this
conjugate ( )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.length = function length() { var w = this.w; var x = this.x; var y = this.y; var z = this.z; return sqrt(w * w + x * x + y * y + z * z); };
Compute the length (norm) of the current Quaternion. @method @return {Number} length of the Quaternion
length ( )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.normalize = function normalize() { var w = this.w; var x = this.x; var y = this.y; var z = this.z; var length = sqrt(w * w + x * x + y * y + z * z); if (length === 0) return this; length = 1 / length; this.w *= length; this.x *= length; this.y *= length; this.z *= length; return this; };
Alter the current Quaternion to be of unit length; @method @return {Quaternion} this
normalize ( )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.set = function set(w, x ,y, z) { if (w != null) this.w = w; if (x != null) this.x = x; if (y != null) this.y = y; if (z != null) this.z = z; return this; };
Set the w, x, y, z components of the current Quaternion. @method @param {Number} w The w component. @param {Number} x The x component. @param {Number} y The y component. @param {Number} z The z component. @return {Quaternion} this
set ( w , x , y , z )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.copy = function copy(q) { this.w = q.w; this.x = q.x; this.y = q.y; this.z = q.z; return this; };
Copy input Quaternion q onto the current Quaternion. @method @param {Quaternion} q The reference Quaternion. @return {Quaternion} this
copy ( q )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.clear = function clear() { this.w = 1; this.x = 0; this.y = 0; this.z = 0; return this; };
Reset the current Quaternion. @method @return {Quaternion} this
clear ( )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.dot = function dot(q) { return this.w * q.w + this.x * q.x + this.y * q.y + this.z * q.z; };
The dot product. Can be used to determine the cosine of the angle between the two rotations, assuming both Quaternions are of unit length. @method @param {Quaternion} q The other Quaternion. @return {Number} the resulting dot product
dot ( q )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.slerp = function slerp(q, t, output) { var w = this.w; var x = this.x; var y = this.y; var z = this.z; var qw = q.w; var qx = q.x; var qy = q.y; var qz = q.z; var omega; var cosomega; var sinomega; var scaleFrom; var scaleTo; cosomega = w * qw + x * qx + y * qy + z * qz; if ((1.0 - cosomega) > 1e-5) { omega = acos(cosomega); sinomega = sin(omega); scaleFrom = sin((1.0 - t) * omega) / sinomega; scaleTo = sin(t * omega) / sinomega; } else { scaleFrom = 1.0 - t; scaleTo = t; } output.w = w * scaleFrom + qw * scaleTo; output.x = x * scaleFrom + qx * scaleTo; output.y = y * scaleFrom + qy * scaleTo; output.z = z * scaleFrom + qz * scaleTo; return output; };
Spherical linear interpolation. @method @param {Quaternion} q The final orientation. @param {Number} t The tween parameter. @param {Vec3} output Vec3 in which to put the result. @return {Quaternion} The quaternion the slerp results were saved to
slerp ( q , t , output )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.toMatrix = function toMatrix(output) { var w = this.w; var x = this.x; var y = this.y; var z = this.z; var xx = x*x; var yy = y*y; var zz = z*z; var xy = x*y; var xz = x*z; var yz = y*z; return output.set([ 1 - 2 * (yy + zz), 2 * (xy - w*z), 2 * (xz + w*y), 2 * (xy + w*z), 1 - 2 * (xx + zz), 2 * (yz - w*x), 2 * (xz - w*y), 2 * (yz + w*x), 1 - 2 * (xx + yy) ]); };
Get the Mat33 matrix corresponding to the current Quaternion. @method @param {Object} output Object to process the Transform matrix @return {Array} the Quaternion as a Transform matrix
toMatrix ( output )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.toEuler = function toEuler(output) { var w = this.w; var x = this.x; var y = this.y; var z = this.z; var xx = x * x; var yy = y * y; var zz = z * z; var ty = 2 * (x * z + y * w); ty = ty < -1 ? -1 : ty > 1 ? 1 : ty; output.x = atan2(2 * (x * w - y * z), 1 - 2 * (xx + yy)); output.y = asin(ty); output.z = atan2(2 * (z * w - x * y), 1 - 2 * (yy + zz)); return output; };
The rotation angles about the x, y, and z axes corresponding to the current Quaternion, when applied in the ZYX order. @method @param {Vec3} output Vec3 in which to put the result. @return {Vec3} the Vec3 the result was stored in
toEuler ( output )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.fromEuler = function fromEuler(x, y, z) { var hx = x * 0.5; var hy = y * 0.5; var hz = z * 0.5; var sx = sin(hx); var sy = sin(hy); var sz = sin(hz); var cx = cos(hx); var cy = cos(hy); var cz = cos(hz); this.w = cx * cy * cz - sx * sy * sz; this.x = sx * cy * cz + cx * sy * sz; this.y = cx * sy * cz - sx * cy * sz; this.z = cx * cy * sz + sx * sy * cz; return this; };
The Quaternion corresponding to the Euler angles x, y, and z, applied in the ZYX order. @method @param {Number} x The angle of rotation about the x axis. @param {Number} y The angle of rotation about the y axis. @param {Number} z The angle of rotation about the z axis. @param {Quaternion} output Quaternion in which to put the result. @return {Quaternion} The equivalent Quaternion.
fromEuler ( x , y , z )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.prototype.fromAngleAxis = function fromAngleAxis(angle, x, y, z) { var len = sqrt(x * x + y * y + z * z); if (len === 0) { this.w = 1; this.x = this.y = this.z = 0; } else { len = 1 / len; var halfTheta = angle * 0.5; var s = sin(halfTheta); this.w = cos(halfTheta); this.x = s * x * len; this.y = s * y * len; this.z = s * z * len; } return this; };
Alter the current Quaternion to reflect a rotation of input angle about input axis x, y, and z. @method @param {Number} angle The angle of rotation. @param {Vec3} x The axis of rotation. @param {Vec3} y The axis of rotation. @param {Vec3} z The axis of rotation. @return {Quaternion} this
fromAngleAxis ( angle , x , y , z )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.multiply = function multiply(q1, q2, output) { var w1 = q1.w || 0; var x1 = q1.x; var y1 = q1.y; var z1 = q1.z; var w2 = q2.w || 0; var x2 = q2.x; var y2 = q2.y; var z2 = q2.z; output.w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2; output.x = x1 * w2 + x2 * w1 + y2 * z1 - y1 * z2; output.y = y1 * w2 + y2 * w1 + x1 * z2 - x2 * z1; output.z = z1 * w2 + z2 * w1 + x2 * y1 - x1 * y2; return output; };
Multiply the input Quaternions. Left-handed coordinate system multiplication. @method @param {Quaternion} q1 The left Quaternion. @param {Quaternion} q2 The right Quaternion. @param {Quaternion} output Quaternion in which to place the result. @return {Quaternion} The product of multiplication.
multiply ( q1 , q2 , output )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.normalize = function normalize(q, output) { var w = q.w; var x = q.x; var y = q.y; var z = q.z; var length = sqrt(w * w + x * x + y * y + z * z); if (length === 0) return this; length = 1 / length; output.w *= length; output.x *= length; output.y *= length; output.z *= length; return output; };
Normalize the input quaternion. @method @param {Quaternion} q The reference Quaternion. @param {Quaternion} output Quaternion in which to place the result. @return {Quaternion} The normalized quaternion.
normalize ( q , output )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.conjugate = function conjugate(q, output) { output.w = q.w; output.x = -q.x; output.y = -q.y; output.z = -q.z; return output; };
The conjugate of the input Quaternion. @method @param {Quaternion} q The reference Quaternion. @param {Quaternion} output Quaternion in which to place the result. @return {Quaternion} The conjugate Quaternion.
conjugate ( q , output )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.clone = function clone(q) { return new Quaternion(q.w, q.x, q.y, q.z); };
Clone the input Quaternion. @method @param {Quaternion} q the reference Quaternion. @return {Quaternion} The cloned Quaternion.
clone ( q )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
Quaternion.dot = function dot(q1, q2) { return q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z; };
The dot product of the two input Quaternions. @method @param {Quaternion} q1 The left Quaternion. @param {Quaternion} q2 The right Quaternion. @return {Number} The dot product of the two Quaternions.
dot ( q1 , q2 )
javascript
Famous/engine
math/Quaternion.js
https://github.com/Famous/engine/blob/master/math/Quaternion.js
MIT
function Mat33(values) { this.values = values || [1,0,0,0,1,0,0,0,1]; }
A 3x3 numerical matrix, represented as an array. @class Mat33 @param {Array} values a 3x3 matrix flattened
Mat33 ( values )
javascript
Famous/engine
math/Mat33.js
https://github.com/Famous/engine/blob/master/math/Mat33.js
MIT